Gaussian distributions with PHP for a 24-hour period

How can I set points on a 24-hour period spread by Gaussian distributions? For example, to have a peak at 10 o’clock?

+3
source share
2 answers

The following code generates a Gaussian distributed random time (in hours, plus fractions of an hour) centered at a given point in time, and with a given standard deviation. Random times can wrap around the clock, especially if the standard deviation is a few hours: this is done correctly. Another “wrapping” algorithm may be more efficient if your standard deviations are very large (many days), but in any case the distribution will be almost uniform.

$peak=10; // Peak at 10-o-clock
$stdev=2; // Standard deviation of two hours
$hoursOnClock=24; // 24-hour clock

do // Generate gaussian variable using Box-Muller
{
    $u=2.0*mt_rand()/mt_getrandmax()-1.0;
    $v=2.0*mt_rand()/mt_getrandmax()-1.0;
    $s = $u*$u+$v*$v;
} while ($s > 1);
$gauss=$u*sqrt(-2.0*log($s)/$s);

$gauss = $gauss*$stdev + $peak; // Transform to correct peak and standard deviation

while ($gauss < 0) $gauss+=$hoursOnClock; // Wrap around hours to keep the random time 
$result = fmod($gauss,$hoursOnClock);     // on the clock

echo $result;
+8

Source: https://habr.com/ru/post/1697702/


All Articles