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.

siren99
  • 195
  • 1
  • 5

4 Answers4

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.

Max Li
  • 5,069
  • 3
  • 23
  • 35
  • 11
    +1 even though for a computer algorithm, the probability of getting the end point is not strictly zero. – Dave Feb 22 '13 at 20:21
  • 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. – NoBackingDown Aug 17 '16 at 20:43
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.

ev-br
  • 24,968
  • 9
  • 65
  • 78
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.

Community
  • 1
  • 1
CmdNtrf
  • 1,163
  • 7
  • 16
  • as a nitpick: it's usually a bad idea to mix `random`s from the standard library and from `numpy`. – ev-br Feb 17 '13 at 16:27
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.

Community
  • 1
  • 1
Dave
  • 7,555
  • 8
  • 46
  • 88