从高斯分布中采样随机值最快的方法是什么? [英] What is the fastest method of sampling random values from a Gaussian distribution?

查看:385
本文介绍了从高斯分布中采样随机值最快的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Box-Muller变换是一种优雅且性能合理的产品高斯分布的随机值采样方法.

The Box-Muller transform, is an elegant and reasonably performant method of sampling random values from a Gaussian distribution.

我正在寻找一种用C#编写的更快的方法.

I'm looking for a faster method clearly written and in C#.

作为参考,这里是Box-Muller实现的一种实现,用作性能比较的基准...

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

在我的Intel Core i7 6700T @ 2.8Ghz(Skylake)上,通过单核测试(使用BenchmarkDotNet),我得到以下性能结果:

On my Intel Core i7 6700T @ 2.8Ghz (Skylake) I get the following performance results on a single core test (using BenchmarkDotNet):

  • Box-Muller: 5450万个样本/秒
  • Ziggurat: 7950万个样本/秒
  • Box-Muller: 54.5M samples/sec
  • Ziggurat: 79.5M samples/sec

在这些测试中,Ziggurat的速度提高了约45%.

So Ziggurat is about 45% faster in those tests.

两个类都使用来自以下类别的 Xoshiro256StarStarRandom Redzen 库作为伪随机源.

Both classes use the Xoshiro256StarStarRandom class from the Redzen library as a source of pseudo-randomness.

这篇关于从高斯分布中采样随机值最快的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆