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

Viewed 52421

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 likely to come up. What is the best way of doing this?

So far, I have used:

2 * numpy.random.rand() - 1

and also:

2 * numpy.random.random_sample() - 1
4 Answers

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.

Related