Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random in C++11 with closed interval

Tags:

c++

random

c++11

The code below generate the number between [0,PI) as default:

#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;
}

I would like generate a number between [0,PI]. To be clear the second bracket must be ], not ) (with closed interval).

Could somebody tell me if the code above is correct?

like image 580
user1519221 Avatar asked Mar 22 '14 18:03

user1519221


1 Answers

That looks correct. Looking here it says the generated value will be in the range [a, b). Since a = 0 and b is the smallest number greater than M_PI, you should get a value in [0, PI].

like image 94
Timothy Shields Avatar answered Nov 20 '22 00:11

Timothy Shields