Skip to content

Instantly share code, notes, and snippets.

@ghostwriter
Created April 2, 2026 21:07
Show Gist options
  • Select an option

  • Save ghostwriter/adca2a52b002ff1661535fd732e9ac93 to your computer and use it in GitHub Desktop.

Select an option

Save ghostwriter/adca2a52b002ff1661535fd732e9ac93 to your computer and use it in GitHub Desktop.
GaussGenerator in PHP
<?php
declare(strict_types=1);
/**
* #BlackLivesMatter - github.com/ghostwriter
**/
use Random\Engine\Mt19937;
use Random\Randomizer;
final class GaussGenerator
{
public function __construct(
private readonly Randomizer $random = new Randomizer()
) {}
public function gauss(float $mu = 0.0, float $sigma = 1.0): float
{
static $next;
if ($next !== null) {
$z = $next;
$next = null;
} else {
$x2pi = $this->random->getFloat(0.0, 1.0) * 2.0 * M_PI;
$g2rad = sqrt(-2.0 * log(1.0 - $this->random->getFloat(0.0, 1.0)));
$z = cos($x2pi) * $g2rad;
$next = sin($x2pi) * $g2rad;
}
return $mu + $z * $sigma;
}
}
@ghostwriter

Copy link
Copy Markdown
Author
<?php

declare(strict_types=1);

/**
 * #BlackLivesMatter - github.com/ghostwriter
 **/

// If you want random
// $generator1 = new GaussGenerator();
// $value1 = $generator1->gauss(0.0, 1.0);
// var_dump(['random' => $value1]);

// If you want reproducible results provide a seed. eg. 1234
$random2 = new Randomizer(new Mt19937(1234));
$generator2 = new GaussGenerator($random2);
$value2 = $generator2->gauss(0.0, 1.0);

var_dump(['reproducible' => $value2]);

// https://3v4l.org/6oIZ5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment