【发布时间】:2011-11-03 05:41:16
【问题描述】:
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);
}
}
【问题讨论】:
-
你有没有用 C# 优雅地实现 Ziggurat 算法?
-
您想要速度和优雅?实施制服比例! Ziggurat(在我看来)丑陋且非常难以调整。
-
@Alexadre。到目前为止,我已经花了几天时间编写一个尽可能优雅的版本,但是是的,它很多比例如复杂。 Box-Muller,尤其是在优化之后!没听说过制服比例,我去研究一下,谢谢指点。
-
不知道为什么关闭它 - 对我来说似乎是一个完全有效的与编程相关的问题,即生成高斯噪声是一个非常普遍的要求,高效/快速地这样做也是如此。
标签: c# performance math gaussian sampling