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.php243 chars10 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