c# - 从高斯分布中抽取随机值的最快方法是什么?

标签 c# performance math gaussian sampling

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/

相关文章:

mysql - 加快 WordPress 缓慢查询速度

c# - PHP/Rails/Django/ASP 网站应该是用 C++ 写的吧?

c# - nHibernate 中 Restrictions.Eq 的命名空间

c# - 如何允许与 Dynamics 服务器的一般连接

c# - 从月份数组中获取一系列值

java - Lambda 表达式参数/声明

c# - "The maximum message size quota for incoming messages (65536) has been exceeded."。即使在设置更大的尺寸之后

java - 如何衡量Java中数据库的性能?

c# - 将数据点转换为像素坐标以进行绘图

java - java中操作的优先级/=运算符