Welcome to WebmasterWorld Guest from 54.83.81.52

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

generating random numbers between 0 and 1

ChrisE

10:34 pm on Nov 17, 2009 (gmt 0)

New User

joined:Oct 28, 2009
posts:33

I'm trying to write a small statistical procedure, and I need random numbers between 0 and 1 evenly distributed.

rand(0,1) and mt_rand(0,1) are both causing me problems. They both seem to return either 0 or 1. I'm not sure if there is some setting my web host has so that the numbers are rounded or what.

I also tried rand( 0, getrandmax()/getrandmax() ) with no luck.

here is the function I'm writing:

function boxmuller()
{
\$a = mt_rand(0,1);
\$b = mt_rand(0,1);
\$bm = sqrt( -2 * log(\$a) ) * cos( 2 * pi() * \$b);
return \$bm;
}

Any thoughts?

In case anyone is curious, Box Muller is a way to generate a standard normal distribution.

pinterface

12:19 am on Nov 18, 2009 (gmt 0)

Junior Member

joined:Jan 28, 2006
posts:96

Well, look at the documentation for rand [us.php.net]:
int rand (int \$min, int \$max)
Note how the return value is an integer. So of course you aren't getting a float.

``rand(0, getrandmax()/getrandmax())``
is closer (you want to divide something by getrandmax()), but think about what it does: it divides getrandmax() by itself, so is equivalent to saying rand(0, 1). To compress a random number between 0 and MAX to be between 0 and 1, you need to divide the random number itself by MAX.

ChrisE

2:04 am on Nov 18, 2009 (gmt 0)

New User

joined:Oct 28, 2009
posts:33

Wow, I feel silly. Thanks. I get sloppy with PHP since it isn't typed as strongly as C++.

2:42 am on Nov 18, 2009 (gmt 0)

Senior Member from US

joined:Apr 14, 2008
posts:2910

Not sure what to tell you about the 'evenly distributed' portion (you could probably accomplish it by storing rotating through a series of 10 possibilities and loop through them, EG 1000000, 1999999 ¦ 2000000, 2999999 ¦ etc.), and you can easily have control over the length of the decimal as follows:

\$number = mt_rand(1000000,9999999);
echo \$number='.'.\$number;
\$number=floatval(\$number);
echo "<br>";
echo gettype (\$number);

Not sure if it helps or not...

ChrisE

3:15 am on Nov 18, 2009 (gmt 0)

New User

joined:Oct 28, 2009
posts:33