What is the best way of getting random numbers in NumPy?

后端 未结 4 1515
梦谈多话
梦谈多话 2020-12-29 23:01

I want to generate random numbers in the range -1, 1 and want each one to have equal probability of being generated. I.e. I don\'t want the extremes to be less

4条回答
  •  独厮守ぢ
    2020-12-29 23:55

    To ensure that the extremes of range [-1, 1] are included, I randomly generate a numpy array of integers in the range [0, 200000001[. The value of the latter integer depends on the final numpy data type that is desired. Here, I take the numpy float64, which is the default type used for numpy arrays. Then, I divide the numpy array with 100000000 to generate floats and subtract with unity. Code for this is:

    >>> import numpy as np
    >>> number = ((np.random.randint(low=0, high=200000001, size=5)) / 100000000) - 1
    >>> print(number)
    [-0.65960772  0.30378946 -0.05171788 -0.40737182  0.12998227]
    

    Make sure not to transform these numpy floats to python floats to avoid rounding errors.

提交回复
热议问题