get a normally distributed random number in php

To generate a normally distributed random number in PHP, we can use the Box-Muller transform algorithm. The Box-Muller method generates a pair of independent standard normal random variables, which can be transformed to generate normally distributed random numbers with any mean and standard deviation.

Here is a PHP code snippet that shows how to generate a normally distributed random number with mean 0 and standard deviation 1 using the Box-Muller transform:

main.php
function randn_bm($mean, $stddev) {
    $x = mt_rand() / mt_getrandmax();
    $y = mt_rand() / mt_getrandmax();
    $z = sqrt(-2 * log($x)) * cos(2 * pi() * $y);
    return $mean + $stddev * $z;
}

// Example usage
$rand_num = randn_bm(0, 1);
243 chars
10 lines

The randn_bm() function takes two arguments: the mean and standard deviation of the normal distribution to generate. The mt_rand() and mt_getrandmax() functions are used to generate uniformly distributed random numbers between 0 and 1. The sqrt() function and cos() function are used to transform the uniform random variables to standard normal random variables with mean 0 and standard deviation 1.

Finally, the function returns the normally distributed random number by transforming the standard normal random variable with the given mean and standard deviation.

gistlibby LogSnag