[Tutor] Need help with random numbers
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 17 Jul 2001 09:14:46 -0700 (PDT)
On Tue, 17 Jul 2001, kevin parks wrote:
> Since it has be brought up, I'd like to know:
>
> random.random() takes no args and returns a float in the range
> 0.0-1.0. How would you return random floats of a different range? say:
> 1.0 - 12.0?
>
> random()
> Return the next random floating point number in the range [0.0,
> 1.0).
There's a good reason why random.random() gives us a floating point
between 0.0 and 1.0: it allows us to "scale" it up to a larger range if we
need it. For example, to get a random float between 0.0 and 10.0 (more
precisely, "[0.0, 10.0)" ), we can do this:
some_number = random.random() * 10.0
It's like "stretching" the random function.
I'm curious: how does random.uniform() actually work?
###
def uniform(self, a, b):
"""Get a random number in the range [a, b)."""
return a + (b-a) * self.random()
###
Yup, that's how they do it as well. They do a little bit more to move the
range from:
[0, b-a)
to
[a, b)
but otherwise, they use the stretching principle.
Hope this helps!