【问题标题】:Generate Random Number Based on Beta Distribution using Boost使用 Boost 生成基于 Beta 分布的随机数
【发布时间】:2011-05-10 01:06:03
【问题描述】:

我正在尝试使用 Boost 根据使用 C++ 的 beta 分布生成随机数。我在网上看到了许多根据 random.hpp 中的分布生成随机数的示例(例如this book)。但是,我无法将它们翻译为使用 beta.hpp 中的 beta 发行版。

谢谢。

【问题讨论】:

    标签: c++ boost statistics random distribution


    【解决方案1】:

    您首先要从 (0,1) 范围内均匀地抽取一个随机数。给定任何分布,然后您可以将该数字插入分布的“分位数函数”,结果就好像从分布中抽取了一个随机值。来自here

    从具有无跳转的 cdf 的任意分布生成随机数的一般方法是使用 cdf 的反函数:G(y)=F^{-1}(y)。如果 u(1), ..., u(n) 是均匀分布在 (0,1) 上的随机数,则 G(u(1)), ..., G(u(n)) 是随机数来自具有 cdf F(x) 的分布的样本。

    那么我们如何获得 beta 分布的分位数函数呢? beta.hpp 的文档是here。你应该可以使用这样的东西:

    #include <boost/math/distributions.hpp>
    using namespace boost::math;
    
    double alpha, beta, randFromUnif; 
    //parameters and the random value on (0,1) you drew
    
    beta_distribution<> dist(alpha, beta);
    double randFromDist = quantile(dist, randFromUnif);
    

    【讨论】:

    • 显然这是一个流行的答案,所以我要补充一点:对于某些分布,您可能有一个在某些点接近垂直的分位数函数,在这种情况下您可能会遇到您传入的randFromUnif 浮点数在通过分位数时没有足够的分辨率来生成随机数的数值/分辨率问题:您最终会得到量化的输出值。因此,请了解您的问题域和分位数函数,以确保您了解这一点!
    【解决方案2】:

    根据 boost 的随机数库演示 Random_demo.cppGenerating integers with different probabilities

    你应该做的是使用“variate_generator”类来绑定你的随机数生成器和分布。

    一个例子可能看起来像

    #include <iostream>
    #include "boost/random.hpp"
    
    int main(int argc, char *argv[])
    {
        int seed = 2018;
        typedef boost::random::mt19937 RandomNumberGenerator;
        typedef boost::random::beta_distribution<> BetaDistribution;
        typedef boost::variate_generator<RandomNumberGenerator&, BetaDistribution> 
        Generator;
        RandomNumberGenerator Rng(seed);
        BetaDistribution distribution(2,5);
        Generator getRandomNumber(Rng,distribution);
        for (int idx = 0 ; idx < 1000 ; ++idx) 
        {
            std::cout << getRandomNumber() << std::endl;
        }
    return 0;
    }
    

    但是,在最近的文档enter link description here 中,似乎 boost 建议将生成器直接传递给分发对象。下面代码的结果是相同的。

    #include <iostream>
    #include "boost/random.hpp"
    
    int main(int argc, char *argv[])
    {
        int seed = 2018;
        typedef boost::random::mt19937 RandomNumberGenerator;
        typedef boost::random::beta_distribution<> BetaDistribution;
        RandomNumberGenerator Rng(seed);
        BetaDistribution distribution(2,5);
        for (int idx = 0 ; idx < 1000 ; ++idx) 
        {
            std::cout << distribution(Rng) << std::endl;
        }
    return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-26
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      相关资源
      最近更新 更多