random number including 1 - i.e. [0,1]

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jun 9 19:05:45 EDT 2009

En Tue, 09 Jun 2009 18:33:39 -0300, Esmail <ebonak at hotmail.com> escribió:

> random.random() will generate a random value in the range [0, 1).
> Is there an easy way to generate random values in the range [0, 1]?
> I.e., including 1?

I think you shouldn't worry about that - the difference may be as small as  
2**-53, or 0.0000000000000001

> I am implementing an algorithm and want to stay as true to the
> original design specifications as possible though I suppose the
> difference between the two max values might be minimal.
> ps: I'm confused by the docs for uniform():
> random.uniform(a, b)
>      Return a random floating point number N such that a <= N <= b for a  
> <= b
> this seems to imply an inclusive range, ie. [a,b]

random() guarantees a semi-open interval (could return 0, but never 1).  
But once you start to operate with the numbers, the limits become fuzzy.

a<b & n>0 => n.a<n.b

The above holds for real numbers but not always for floating point  
arithmetic, so one cannot guarantee the semi-open interval anymore:

py> a=10.0
py> b=11.0
py> z = 0.9999999999999999  # assume random.random returned this
py> z<1
py> a+(b-a)*z < b # the expression used for uniform(a,b)
py> a+(b-a)*z

The docs are already updated to reflect this:

Gabriel Genellina

More information about the Python-list mailing list