# [Tutor] random floats in a range greater than 0.0-1.0

**Danny Yoo
**
dyoo@hkn.eecs.berkeley.edu

*Wed, 13 Feb 2002 14:06:11 -0800 (PST)*

On Thu, 14 Feb 2002, kevin parks wrote:
>* I see in the random module that you can get random integers with
*>* randrange and you can get 0-1.0 floats, but how does one get floats in
*>* a range (of say 0-100, 50-128, or whatever...), do you just use the
*>* regular random (0-1) floats and scale the output?
*
I think scaling would be the way to go on this one. I can't think offhand
of a function in the random module that will do this, but cooking up such
a function should be too bad.
This sounded like a fun problem, so I've cooked up such a function.
*** Spoiler space ahead ***
*** Spoiler space engaged ***
Here's a function called randfrange() that returns a random floating-point
number:
###
>>>* import random
*>>>* def randfrange(a, b=None):
*... """Returns a random float in the range [a, b)."""
... if b == None:
... a, b = 0, a
... return random.random() * (b-a) + a
...
>>>* randfrange(50, 128)
*97.318483168501587
>>>* randfrange(50, 128)
*81.658069841691457
>>>* randfrange(2, 2)
*2.0
>>>* randfrange(2, 3)
*2.1495229573274912
>>>* randfrange(42, 43)
*42.372700368345136
>>>* randfrange(50)
*2.7482513388830343
>>>* randfrange(100)
*24.518574974538375
###
Hope this helps!