The Box-Muller transform, is an elegant and reasonably performant method of sampling random values from a Gaussian distribution.
I'm looking for a faster method clearly written and in C#.
For reference here's an implementation of the Box-Muller Implementation to act as a baseline for performance comparisons...
public class GaussianGenerator
{
FastRandom _rng = new FastRandom();
double? _spareValue = null;
/// <summary>
/// Get the next sample point from the gaussian distribution.
/// </summary>
public double NextDouble()
{
if(null != _spareValue)
{
double tmp = _spareValue.Value;
_spareValue = null;
return tmp;
}
// Generate two new gaussian values.
double x, y, sqr;
// We need a non-zero random point inside the unit circle.
do
{
x = 2.0 * _rng.NextDouble() - 1.0;
y = 2.0 * _rng.NextDouble() - 1.0;
sqr = x * x + y * y;
}
while(sqr > 1.0 || sqr == 0);
// Make the Box-Muller transformation.
double fac = Math.Sqrt(-2.0 * Math.Log(sqr) / sqr);
_spareValue = x * fac;
return y * fac;
}
/// <summary>
/// Get the next sample point from the gaussian distribution.
/// </summary>
public double NextDouble(double mu, double sigma)
{
return mu + (NextDouble() * sigma);
}
}
For the record here's a clearly written implementation, with unit tests:
ZigguratGaussianDistribution.cs
On my Intel Core i7 6700T @ 2.8Ghz (Skylake) I get the following performance results on a single core test (using BenchmarkDotNet):
So Ziggurat is about 45% faster in those tests.
Both classes use the Xoshiro256StarStarRandom class from the Redzen library as a source of pseudo-randomness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With