使用boost :: random库获取整数随机值而不是实际值

时间:2012-07-09 23:29:49

标签: c++ boost boost-random

我正在尝试使用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;

但没有......(总是整数值)

1 个答案:

答案 0 :(得分: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,因此它可以在不设置此项的情况下工作,但是......