php random normal distribution curve

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
SmokyBarnable
Forum Contributor
Posts: 105
Joined: Wed Nov 01, 2006 5:44 pm

php random normal distribution curve

Post by SmokyBarnable »

I need to find a random number +-10% of 2000 which i know how to do with mt_rand but I need it to be a bell curve normal distribution. Any tips on how I can do this?
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: php random normal distribution curve

Post by Eran »

Check out the comments in the manual -
http://www.php.net/manual/en/function.rand.php#53784
User avatar
SmokyBarnable
Forum Contributor
Posts: 105
Joined: Wed Nov 01, 2006 5:44 pm

Re: php random normal distribution curve

Post by SmokyBarnable »

Thanks. I'm using these functions and it seems to work well. Why is only one independent variable needed in function gauss()?

Code: Select all

function gauss()
{   // N(0,1)
    // returns random number with normal distribution:
    //   mean=0
    //   std dev=1
   
    // auxilary vars
    $x=random_0_1();
    $y=random_0_1();
   
    // two independent variables with normal distribution N(0,1)
    $u=sqrt(-2*log($x))*cos(2*pi()*$y);
    $v=sqrt(-2*log($x))*sin(2*pi()*$y);
   
    // i will return only one, couse only one needed
    return $u;
}
 
function gauss_ms($m=0.0,$s=1.0)
{   // N(m,s)
    // returns random number with normal distribution:
    //   mean=m
    //   std dev=s
   
    return gauss()*$s+$m;
}
 
function random_0_1()
{   // auxiliary function
    // returns random number with flat distribution from 0 to 1
    return (float)rand()/(float)getrandmax();
}
 
Post Reply