在c ++ 11中生成分布

时间:2015-07-06 15:58:03

标签: c++ c++11 boost

我使用以下代码在[0,1]和[0,1]之间的正态分布之间生成指数分布:

#include <iostream>
#include <algorithm>
#include "boost/random.hpp"
#include "boost/generator_iterator.hpp"
using namespace std;

int main()
{
   typedef boost::mt19937 RNGType;
   RNGType rng;

   //for generating exponential distribution
   boost::exponential_distribution<0,1> one_to_six;
   boost::variate_generator< RNGType, boost::exponential_distribution<> >
                dice(rng, one_to_six);
   double number = dice();                    
   cout<<"random number according to exponential distribution="<<number<<"\n";

   //for generating normal distribution
   boost::normal_distribution<0,1> one_to_six1;
   boost::variate_generator< RNGType, boost::normal_distribution<> >
                dice1(rng, one_to_six1);
   double number1 = dice1();                    
   cout<<"random number according to normal distribution="<<number<<"\n";
}

但我不知道为什么我的代码出错了。有人可以帮我弄清楚我哪里出错了。我正在使用c ++ 11。

我得到的错误是:

 no known conversion for argument 2 from ‘int’ to ‘boost::normal_distribution<>’

正如Barry所建议的,我试图将代码更改为:

int main()
{
   typedef boost::mt19937 RNGType;
   RNGType rng;

   //for generating exponential distribution
   boost::exponential_distribution<double> one_to_six;;
   boost::variate_generator< RNGType, boost::exponential_distribution<> >
                dice(rng, one_to_six);
   double number = dice();                    
   cout<<"random number according to exponential distribution="<<number<<"\n";

   //for generating normal distribution
   boost::normal_distribution<double> one_to_six1;
   boost::variate_generator< RNGType, boost::normal_distribution<> >
                dice1(rng, one_to_six1);
   double number1 = dice1();                    
   cout<<"random number according to normal distribution="<<number<<"\n";
}

但我仍然收到错误:注意:boost :: variate_generator :: variate_generator(Engine,Distribution)

1 个答案:

答案 0 :(得分:3)

始终发布并阅读编译器错误。在这种情况下,非常明确:

main.cpp:13:36: error: template argument for template type parameter must be a type
   boost::exponential_distribution<0,1> one_to_six;
                                   ^
/usr/local/include/boost/random/exponential_distribution.hpp:37:16: note: template parameter is declared here
template<class RealType = double>
               ^
main.cpp:20:31: error: template argument for template type parameter must be a type
   boost::normal_distribution<0,1> one_to_six;
                              ^
/usr/local/include/boost/random/normal_distribution.hpp:256:16: note: template parameter is declared here
template<class RealType = double>
               ^
2 errors generated.

boost::exponential_distribution定义为:

template <class RealType = double,
          class Policy   = policies::policy<> >
class exponential_distribution;

所以你可能需要:

boost::exponential_distribution<double> one_to_six;

您的normal_distribution变量也是如此。另外,这应该采用不同的名称,因为目前在同一范围内有两个名为one_to_six的变量。