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
Your approach is fine. An alternative is to use the function
numpy.random.uniform()
:Regarding the probability for the extremes: If it would be idealised, continuous random numbers, the probability to get one of the extremes would be 0. Since floating point numbers are a discretisation of the continuous real numbers, in realitiy there is some positive probability to get some of the extremes. This is some form of discretisation error, and it is almost certain that this error will be dwarved by other errors in your simulation. Stop worrying!
Note that
numpy.random.rand
allows to generate multiple samples from a uniform distribution at one call:It also allows to generate samples in a given shape:
As You said, uniformly distributed random numbers between [-1, 1) can be generated with:
From the documentation for
numpy.random.random_sample
:Per Sven Marnach's answer, the documentation probably needs updating to reference
numpy.random.uniform
.