如何使用boost weibull分发库进行随机数生成?

时间:2015-04-02 15:55:57

标签: c++ boost

我想在C ++中使用weibull分布生成随机数。谁能给我一些提示?

由于

2 个答案:

答案 0 :(得分:5)

我认为这可以回答您的问题:c++ References

// weibull_distribution
#include <iostream>
#include <random>

int main()
{
  const int nrolls=10000;  // number of experiments
  const int nstars=100;    // maximum number of stars to distribute

  std::default_random_engine generator;
  std::weibull_distribution<double> distribution(2.0,4.0);

  int p[10]={};

  for (int i=0; i<nrolls; ++i) {
    double number = distribution(generator);
    if (number<10) ++p[int(number)];
  }

  std::cout << "weibull_distribution (2.0,4.0):" << std::endl;

  for (int i=0; i<10; ++i) {
    std::cout << i << "-" << (i+1) << ": ";
    std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
  }

  return 0;
}

可能的输出: weibull_distribution(2.0,4.0):

0-1: ******
1-2: ***************
2-3: *********************
3-4: ********************
4-5: ***************
5-6: ***********
6-7: *****
7-8: **
8-9: *
9-10: 

答案 1 :(得分:0)

以下是使用Boost Library的解决方案:

#include <iostream>
using namespace std;

#include <boost/random/mersenne_twister.hpp>        // For boost::mt19937
#include <boost/random/variate_generator.hpp>
#include <boost/random/weibull_distribution.hpp>

#include <iostream>
using namespace std; 

int main() {
    // Choose precision
    cout.precision(10);
    cout << endl;

    // To get random generated numbers:
    boost::mt19937 rng(12);
    double shape = 3.0;
    double scale = 0.5;
    boost::random::weibull_distribution<> myWeibull2(shape, scale);
    boost::random::variate_generator<boost::mt19937&, boost::random::weibull_distribution<> > rand_Weibull(rng, myWeibull2);

    cout << "Random numbers generated from a Weibull distribution:" << endl;
    double rn;
    for (int i=0; i < 10; ++i)
    {
        rn = rand_Weibull();
        cout << rn << endl;
    }
    cout << endl;

    return 0;
}