generating random numbers in perl

Discussion in 'Perl Misc' started by mahurshi, Mar 23, 2006.

1. mahurshiGuest

i have been trying to generate random numbers in perl
and so far, i have been partially successful.

my code is as follows:

for (\$i = 1; \$i <= 100; \$i++)
{
\$test = rand(100000);
printf ("%e\n", \$test);
}

i am pasting a sample output here:

1.710742e+04
9.492561e+04
3.755295e+04
6.329775e+04
8.602091e+04
8.700460e+03
5.051776e+04
3.425434e+04
8.534643e+03

as you can see, most of the output is in the order of 10^4 and 10^3

i was wondering if there is a way to increase the "swing" in the
randomness
of these numbers, so that i can really see a better mix of numbers of
different magnitudes.

Mahurshi Akilla

mahurshi, Mar 23, 2006

2. A. Sinan UnurGuest

So you want to bias the random number generator?

The probability of drawing x <= 1000 is 1% and the probability of
drawing x <= 100 is 0.1%.

Using the binomial formula, you can easily figure out the expected
number of draws under 1000 out of 100,000 numbers in 100 draws. Yes,
that is correct. The expected number of draws less than 1000 out of 100
draws from [0 .. 100,000) is exactly one.

Now, if you don't want the numbers to be independently and uniformly
distributed, then that's a different task. Decide what probability
distribution you want to use, and use it.

Sinan

A. Sinan Unur, Mar 23, 2006

3. xhosterGuest

It is hard to see why that should not be the case.

Maybe this would be more to your liking:

\$test = exp(rand()*11.5);

Xho

xhoster, Mar 23, 2006
4. mahurshiGuest

just curious, is there a reason why you picked that ?

Mahurshi Akilla

mahurshi, Mar 23, 2006
5. xhosterGuest

I choose exponentiation because it is by far the most natural way to
generate data that varies over many orders of magnitude. I choose 11.5
because that puts the maximum value at about 100_000 (exp(11.5) ~
98715.77), which is close to the maximum value possible under your original
script.

Xho

xhoster, Mar 23, 2006
6. Dr.RuudGuest

schreef:
\$test = exp rand 11.5;

perl -e 'printf "%9.3f\n", exp rand 11.5 for 1..20'

Dr.Ruud, Mar 23, 2006