2

我正在尝试使用boost::random库获得真正的随机值。这是我的代码:

#include <iostream>

#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>

boost::random::mt19937 eng = boost::random::mt19937();
boost::random::uniform_real_distribution<double> urd =
   boost::random::uniform_real_distribution<double>(0,20);

for (int i = 0; i <= 100; i++)
   std::cout << urd(eng) << std::endl;

但我得到 0 到 20 之间的整数。

我能怎么做?

我还尝试了另一个引擎:

#include <iostream>

#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/lagged_fibonacci.hpp>

boost::random::lagged_fibonacci607 eng = boost::random::lagged_fibonacci607();
boost::random::uniform_real_distribution<double> urd =
   boost::random::uniform_real_distribution<double>(0,20);

for (int i = 0; i <= 100; i++)
   std::cout << urd(eng) << std::endl;

但什么都没有......(总是整数值)

4

1 回答 1

3

在输出之前设置精度怎么样?std::cout.precision(15);?

或使用:

std::cout.precision(std::numeric_limits<double>::digits10);

例子

#include <iostream>
#include <limits>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>

int main()
{
    boost::random::mt19937 eng = boost::random::mt19937();
    boost::random::uniform_real_distribution<double> urd =
    boost::random::uniform_real_distribution<double>(0,20);

    std::cout.precision(std::numeric_limits<double>::digits10);
    for (int i = 0; i <= 100; i++)
    {
       std::cout << urd(eng) << std::endl;
    }
}

的默认精度std::cout设置为6,所以它应该可以在不设置的情况下工作,但是......

于 2012-07-09T23:33:55.113 回答