【问题标题】:Getting integer random values instead of real values using boost::random library使用 boost::random 库获取整数随机值而不是实际值
【发布时间】:2012-07-09 23:29:49
【问题描述】:

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

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

【问题讨论】:

  • 什么都没有是什么意思?您没有得到任何输出或意外/意外的输出吗?
  • 表示我总是得到整数随机值
  • 您的示例代码非常适合我。 2.50366 6.34199 15.275 19.0044 9.81178 0.688922 13.2722 8.77489 2.51793 7.63117 4.20418 15.3103 ...
  • 是的,对不起,杰西是对的!精度问题!

标签: c++ boost boost-random


【解决方案1】:

在输出之前设置精度怎么样? 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,因此无需设置它也应该可以工作,但是...

【讨论】:

  • @Andry:请尝试我发布的示例。
猜你喜欢
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 2010-11-09
  • 2022-11-17
  • 1970-01-01
  • 2015-01-27
  • 1970-01-01
  • 2011-10-18
相关资源
最近更新 更多