get a random number from a normal distribution with a mean of 0 and a standard deviation of 1 in php

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.php
function generate_normal_random_number() {
    $u1 = 1.0 - rand() / getrandmax();
    $u2 = 1.0 - rand() / getrandmax();
    $z = sqrt(-2.0 * log($u1)) * cos(2.0 * M_PI * $u2);
    return $z;
}

// Generate a random number from the normal distribution
$random_number = generate_normal_random_number();

echo $random_number;
324 chars
12 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