Reputation: 71
So according to numpy's documentation here: https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.random.uniform.html, they say that the random values generated belong to the set [lower, upper) i.e. all values are >= lower, and less than upper. Is there any way to make this a stricter bound, i.e. all values are > lower? I have a particular case in which I want to ensure that all random values lie between 0 and k, but should not be equal to 0, as that will cause my program to crash. Any workarounds/other libraries which can help me?
Upvotes: 1
Views: 2670
Reputation: 36608
The chance of actually getting 0 from a call to np.ranodm.uniform(0,k)
is practially zero. If you want to guarantee it, you can set a lower value that is very small.
epsilon = np.finfo(np.float).eps
np.random.uniform(epsilon, k)
Edit:
For my machine, epsilon
is 2.2204460492503131e-16
. The chance of getting any specific number should be roughly 1 / (1/epsilon)
, or 1 / 4503599627370496
.
As an example, the following code checks for 0.0
occurring in a million length array of np.random.normal(0,1)
:
counter = 0
stop = False
while not stop:
x = np.random.normal(0,1, size=1000000)
stop = any(x==0.0)
counter += 1
print('\rIteration: {} '.format(counter), end='')
I am currently over 75,000 iteration without a zero occurring. This is not a perfect test, clearly, but it does demonstrate the minute chance of actually getting a zero.
Upvotes: 4
Reputation: 23637
I want to ensure that all random values lie between 0 and k, but should not be equal to 0
If you have numbers in the range low <= u < high
you can easily convert them to low < r <= high
:
r = high - np.random.uniform(0, high - low)
Of course this is only useful if r
is allowed to include high
but not low
.
Upvotes: 1