random number including 1 - i.e. [0,1]
Paul McGuire
ptmcg at austin.rr.com
Tue Jun 9 20:39:10 EDT 2009
On Jun 9, 4: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?
>
Are you trying to generate a number in the range [0,n] by multiplying
a random function that returns [0,1] * n? If so, then you want to do
this using: int(random.random()*(n+1)) This will give equal chance of
getting any number from 0 to n.
If you had a function that returned a random in the range [0,1], then
multiplying by n and then truncating would give only the barest sliver
of a chance of giving the value n. You could try rounding, but then
you get this skew:
0 for values [0, 0.5) (width of 0.5)
1 for value [0.5, 1.5) (width of 1)
...
n for value [n-0.5, n] (width of ~0.50000000000000001)
Still not a uniform die roll. You have only about 1/2 the probability
of getting 0 or n as any other value.
If you want to perform a fair roll of a 6-sided die, you would start
with int(random.random() * 6). This gives a random number in the
range [0,5], with each value of the same probability. How to get our
die roll that goes from 1 to 6? Add 1. Thus:
die_roll = lambda : int(random.random() * 6) + 1
Or for a n-sided die:
die_roll = lambda n : int(random.random() * n) + 1
This is just guessing on my part, but otherwise, I don't know why you
would care if random.random() returned values in the range [0,1) or
[0,1].
-- Paul
More information about the Python-list
mailing list