【问题标题】:Boost Random Number Not Change提升随机数不变
【发布时间】:2019-10-14 03:48:02
【问题描述】:

在 CPP 中使用 boost 库生成随机数时遇到一些问题。当我尝试打印输出随机数时,该值返回相同的值。这是我的代码。

for(int i = 0; i < TOTAL_PARTICLES; i++) {
            boost::random::mt19937 engine(static_cast<unsigned int>(std::time(0)));                    
            randn = boost::bind(boost::random::uniform_real_distribution<>(-2.5, 2.5), engine);                            
            cout << "Random : " << randn() << endl;
        }

【问题讨论】:

  • 您总是使用相同的种子 - 尝试将引擎置于 for 循环之外
  • 不同的生成器,同样的问题:stackoverflow.com/questions/9459035/… 顺便说一句,我只需在谷歌中输入你的标题就发现了这一点,因此被否决了;)

标签: c++ random boost random-seed


【解决方案1】:

您每次都使用相同的引擎种子,因此您每次都会收到相同的随机数集。因此,只需像这样在 for 循环之外为引擎播种:

boost::random::mt19937 engine(static_cast<unsigned int>(std::time(0)));                    
for(int i = 0; i < TOTAL_PARTICLES; i++) 
{
    randn = boost::bind(boost::random::uniform_real_distribution<>(-2.5, 2.5), engine);                            
    cout << "Random : " << randn() << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2011-06-14
    • 2017-12-23
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多