c++ - C++11 中的随机闭区间

标签 c++ c++11 random

下面的代码默认生成[0,PI)之间的数字:

#include <iostream>
#include <random>
int main()
{
  std::random_device rd;
  std::default_random_engine re(rd());
  //std::uniform_real_distribution<double> unifPhi(0., M_PI);//[0.,PI) // <- default
  std::uniform_real_distribution<double> unifPhi{0.0, std::nextafter(M_PI, 2.*M_PI)};//probably [0.,PI]
  for(unsigned int i=0u;i<10u;++i)
    std::cout << unifPhi(re) << std::endl;

  return 0;
}

我想在 [0,PI] 之间生成一个数字。要清楚,第二个括号必须是 ],而不是 )(闭区间)。

谁能告诉我上面的代码是否正确?

最佳答案

看起来是正确的。寻找 here它表示生成的值将在 [a, b) 范围内。由于 a = 0b 是大于 M_PI 的最小数字,您应该在 [0, PI].

关于c++ - C++11 中的随机闭区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22581737/

相关文章:

javascript - 在 4x4 板上平均分配字母

c++ - 错误 : no matching member function for call to 'reset' (shared pointers)

c++ - 理解递归代码的演练

c++ - 使用 Enter 继续并使用 esc 退出 C++

c++ - 保存文件或文件夹的时间戳?

c++ - 使用模板元编程计算数据编译时间

c++ - 将 JSON 文件添加到插件 qmake 项目

c++ - 尝试用分隔符连接 C 字符串数组

python - random.randint 非整数? [Python]

hash - 加密哈希算法可以用作 PRNG 吗?