Drawing floating numbers with [0, 1] from uniform distribution by using numpy
Asked Answered
L

4

11

I'm currently trying to draw floating numbers from a uniform distribution.

The Numpy provides numpy.random.uniform.

import numpy as np
sample = np.random.uniform (0, 1, size = (N,) + (2,) + (2,) * K)

However, this module generates values over the half-open interval [0, 1).

How can I draw floating numbers with [0, 1] from a uniform distribution?

Thanks.

Landon answered 17/2, 2013 at 14:47 Comment(1)
What is the use case where this makes a difference?Moyers
K
11

It doesn't matter if you're drawing the uniformly distributed numbers from (0,1) or [0,1] or [0,1) or (0,1]. Because the probability of getting 0 or 1 is zero.

Kauri answered 17/2, 2013 at 14:56 Comment(2)
+1 even though for a computer algorithm, the probability of getting the end point is not strictly zero.Moyers
I would also simply ignore it. For the highly improbably event that 1 is sampled, rejecting it is a possibility, but likely too expensive to be worthwhile.Colossians
J
4

random_integers generates integers on a closed interval. So, if you can recast the actual problem of yours into using integers, you're all set. Otherwise, you may consider if granularity of 1./MAX_INT is sufficient to your problem.

Joris answered 17/2, 2013 at 16:26 Comment(0)
D
2

From the standard Python random.uniform documentation :

The end-point value b may or may not be included in the range depending on floating-point rounding in the equation a + (b-a) * random().

So basically, the inclusion of the end point is strictly based on the floating-point rounding scheme used. Therefore, to include 1.0, you need to define the precision required by your operation and round the random number accordingly. If you do not have a defined precision for your problem, you can use numpy.nextafter. Its usage was covered by a previous answer.

Dyedinthewool answered 17/2, 2013 at 16:8 Comment(1)
as a nitpick: it's usually a bad idea to mix randoms from the standard library and from numpy.Joris
M
0

If your software depends on the difference between [0,1) and [0,1] then you should probably roll your own random number generator, possibly the one mentioned here in order to ensure that it meets these stringent requirements.

Moyers answered 22/2, 2013 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.