To generate a random number from a normal distribution with mean 0 and standard deviation 1 in PHP, you can use the rand()
and sqrt()
functions to generate two random numbers in the range [0, 1)
and use the Box-Muller transform to convert them into a single random number in the desired distribution.
Here is a code snippet that demonstrates this:
main.php324 chars12 lines
In this code, the generate_normal_random_number()
function uses the Box-Muller transform to generate a random number from the normal distribution with mean 0 and standard deviation 1. The values of $u1
and $u2
are generated using the rand()
function, which returns a random integer between 0 and getrandmax()
. The log()
function computes the natural logarithm of $u1
, and the cos()
function computes the cosine of 2 * pi * $u2
. The sqrt()
function then multiplies these values to get the final random number in the desired distribution.
gistlibby LogSnag