C++ 11中的随机,具有闭区间

use*_*221 6 c++ random c++11

下面的代码生成[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;
}
Run Code Online (Sandbox Code Playgroud)

我想在之间生成一个数字[0,PI].要明确第二个括号必须是],而不是)(具有封闭间隔).

有人可以告诉我上面的代码是否正确吗?

Tim*_*lds 3

这看起来是正确的。看这里它说生成的值将在范围内[a, b)。由于a = 0b是大于 的最小数M_PI,因此您应该在 中得到一个值[0, PI]