提升随机数不变

Boost Random Number Not Change

本文关键字:随机数      更新时间:2023-10-16

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

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 循环之外播种引擎,如下所示:

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;
}