Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

generating random numbers between 0 and 1

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

New User

5+ Year Member

joined:Oct 28, 2009
votes: 0

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.

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

Junior Member

10+ Year Member

joined:Jan 28, 2006
votes: 0

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.
2:04 am on Nov 18, 2009 (gmt 0)

New User

5+ Year Member

joined:Oct 28, 2009
votes: 0

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 

WebmasterWorld Senior Member themadscientist is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

joined:Apr 14, 2008
votes: 62

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;
echo "<br>";
echo gettype ($number);

Not sure if it helps or not...

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

New User

5+ Year Member

joined:Oct 28, 2009
votes: 0

Generally, the rand() functions in various languages are pretty even. Now that my Box Muller function is working, the results from the Monte Carlo simulation are spot on with what I was getting from running the sim in MS Excel. So that is, as they say, good enough for government work!

Thanks for the help!


Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members