开发者

How to generate random numbers in C++ using <random> header members?

I learned to program in C# and have started to learn C++. I'm using the Visual Studio 2010 IDE. I am trying to generate random numbers with the distribution classes available in <random>. For example I tried doing the following:

    #include <random>
std::normal_distribution<double> *normal = new normal_distribution<double>(0.0, 0.0);
std::knuth_b *engine = new knuth_b();
std::variate_generator<knuth_b, normal_distribution<double>> *rnd;  
rnd = new variate_generator<knuth_b, normal_distribution<double>>(engine, normal);

The last line gives a compiler error: IntelliSense: no instance of constructor "std::tr1::variate_generator<_Engin开发者_如何学运维e, _Distrib>::variate_generator [with _Engine=std::tr1::knuth_b, _Distrib=std::tr1::normal_distribution]" matches the argument list

My arguments look ok to me, what am I doing wrong? When the variate_generator class here is instantiated, which method do you call to get the next random number i.e. .NET's System.Random.Next()?


There is no variate_generator in C++0x, but std::bind works just as well. The following compiles and runs in GCC 4.5.2 and MSVC 2010 Express:

#include <random>
#include <functional>
#include <iostream>
int main()
{
    std::normal_distribution<> normal(10.0, 3.0); // mean 10, sigma 3
    std::random_device rd;
    std::mt19937 engine(rd()); // knuth_b fails in MSVC2010, but compiles in GCC
    std::function<double()> rnd = std::bind(normal, engine);

    std::cout << rnd() << '\n';
    std::cout << rnd() << '\n';
    std::cout << rnd() << '\n';
    std::cout << rnd() << '\n';
}

PS: avoid new when you can.


ALERT: Note that the above solution binds a copy of the engine, not a reference to the engine. Thus, if you also do: std::function rnd2 = std::bind(normal, engine); then the rnd object and the rnd2 object will produce the exact same sequence of random numbers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜