[Tutor] random floats in range func

kevin parks kp8 at mac.com
Thu May 6 04:51:49 EDT 2004


One of the things i am constantly having to do, (and one of the odd 
things left out of the random
module is to get a random FLOAT in a certain range, like say i want a 
random value from 4 to 9
i would do:

x = ((random.random()*5) + 4) # give us random floats in range 4-9


my scripts are full of these. What might be nice, would be to wrap this 
in a func that i can put in
a module and then just import and make my code more readable and easier 
to write. I could do:



def irand(base, upperbound):
     scale = upperbound - base
     return (random.random() * scale) + base


which works fine... but i would like to have it be smart and not just 
barf if some one puts in erroneous values
like making the base higher than the upperbound, etc. Is there a way to 
make this more rubust like that AND
i wouldn't mind being able to quantize the out put so that i would say 
round to the nearest .1 or .25 or .333 or something.... of course in 
the case of rounding to 1 we already have randrange in the random 
module.


cheers,

kevin




More information about the Tutor mailing list