Re: Generating Random Numbers with Normal Distribution

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Dec 10, 2007 2:28 PM, AmirBehzad Eslami <behzad.eslami@xxxxxxxxx> wrote:

> Dear list,
>
> For some computer-based simulation, i need to
> generate random numbers that have a normal distribution.
>
> It seems that PHP's rand() and mt_rand() functions return
> uniformly distributed numbers which is not suitable for
> simulation purposes.
>
> Is there any way to generate random numbers with
> normal distribution in PHP?
>

this is straight from a comment on the rand() documentation:
http://us3.php.net/rand

-nathan

Random numbers with Gauss distribution (normal distribution).
A correct alghoritm. Without aproximations, like Smaaps'
It is specially usefull for simulations in physics.
Check yourself, and have a fun.

<?php

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();
}

?>

JanS
student of astronomy
on Warsaw University

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux