Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating number from binomial distribution using C++ TR1

Tags:

c++

random

tr1

I am trying to use the following code (taken from the internet) to generate numbers from binomial distribution. It compiles but one execution it hangs. (I am using g++ on mac.)

Could someone suggest a working code to generate numbers from binomial distribution using C++ TR1 library features?

#include <tr1/random>
#include <iostream>
#include <cstdlib>

using namespace std;
using namespace std::tr1;

int main()
{
  std::tr1::mt19937 eng; 
  eng.seed(time(NULL));
  std::tr1::binomial_distribution<int, double> roll(5, 1.0/6.0);
  std::cout << roll(eng) << std::endl;
  return 0;
}
like image 305
Madhav Jha Avatar asked Feb 21 '13 22:02

Madhav Jha


1 Answers

Here is working code:

#include <iostream>
#include <random>

int main() {
  std::random_device rd;
  std::mt19937 gen(rd());
  std::binomial_distribution<> d(5, 1.0/6.0);
  std::cout << d(gen) << std::endl;
}

You can check its result here, and it works with recent GCC and Clang versions. Please note that it is generally better to use the random_device instead of time to get a seed.

Compile it with the --std=c++11.

like image 128
DennisL Avatar answered Oct 18 '22 14:10

DennisL