Box-Muller transform , 是一种从高斯分布中抽取随机值的优雅且性能合理的方法。
我正在寻找一种用 C# 清楚地编写的更快的方法。
作为引用,这里有一个 Box-Muller 实现的实现,作为性能比较的基准......
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);
}
}
最佳答案
作为记录,这里有一个清晰的书面实现,带有单元测试:
ZigguratGaussianDistribution.cs
在我的英特尔酷睿 i7 6700T @ 2.8Ghz (Skylake) 上,我在单核测试中获得了以下性能结果(使用 BenchmarkDotNet):
- Box-Muller:54.5M 样本/秒
- 金字塔:79.5M 样本/秒
因此 Ziggurat 在这些测试中的速度提高了大约 45%。
两个类都使用 Xoshiro256StarStarRandom来自 Redzen 的类(class)图书馆作为伪随机性的来源。
关于c# - 从高斯分布中抽取随机值的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7183229/