[Tutor] random floats in range func

denis denis.spir at free.fr
Thu May 6 06:08:41 EDT 2004


----- Original Message -----
From: kevin parks <kp8 at mac.com>
To: <tutor at python.org>
Sent: Thursday, May 06, 2004 10:51 AM
Subject: Re: [Tutor] random floats in range func


> 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

Here, you obviously write the solution along with the problem...

> 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.

something like that (?) :

>>> def fraction_round(x,fraction_int):
...  x *= fraction_int    # trick 1 of 2 : mult
...  x = round(x)
...  return float(x) / fraction_int    # trick 2 of 2 : div

round to 1/3 :

>>> for i in range(10):
...  print fraction_round(random.random(),3)
...
1.0
0.333333333333
0.666666666667
1.0
0.333333333333
0.666666666667
0.0
1.0
0.666666666667
0.333333333333

of, course, the range may be other than 0->1 ; say 10->15, and round to 1/2
:

>>> for i in range(10):
...  print fraction_round(random.random()*5+10,2)
...
10.0
11.5
13.0
12.5
10.5
13.5
13.5
14.5
15.0
14.0

> cheers,
>
> kevin


cheers,
denis




More information about the Tutor mailing list