random number including 1 - i.e. [0,1]
Carl Banks
pavlovevidence at gmail.com
Wed Jun 10 23:45:41 CEST 2009
On Jun 9, 2:33 pm, Esmail <ebo... at hotmail.com> wrote:
> Hi,
>
> 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 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.
Well, I guess someone should actually describe a solution to this
rather than debate the necessity, if only for academic interest.
So, in order to do this for real:
Generate a random integer the range [0,2**53+1), probably the easiest
thing is to get a 64 bit integer and scale it using integer division
(which will also help to minimize selection bias). random.randrange
probably does something like this already.
If the number is exactly 2**53, return 1.0. Else stuff the bits of
the number into the mantissa of a double, along with -1 as the
exponent, and return that.
Implementation left as exercise, mostly because it really won't make a
difference.
Carl Banks
More information about the Python-list
mailing list