简体   繁体   中英

Generating number from binomial distribution using C++ 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;
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM