本文介绍了C ++中来自正态分布的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为C ++的完整入门者,我想从正态分布中生成一个随机数.

As a complete beginner to C++, I would like to generate a random number from a normal distribution.

使用以下代码(源自此帖子),我可以这样做:

With the following code (derived from this post), I am able to do so:

#include <iostream>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>

using namespace std;

int main()
{
    boost::mt19937 rng(std::time(0)+getpid());
    boost::normal_distribution<> nd(0.0, 1.0);
    boost::variate_generator<boost::mt19937&,
                             boost::normal_distribution<> > rnorm(rng, nd);

    cout<< rnorm();
  return 0;
}

由于代码很精细(在我看来),所以我认为可能会有一个更直接的解决方案:

Since the code is quite elaborate (in my view), I thought that there might be a more straightforward solution:

#include <iostream>
#include <random>

using namespace std;

int main()
{
    default_random_engine generator;
    normal_distribution<double> distribution(0.0,1.0);

    cout << distribution(generator);
    return 0;
}

虽然我可以生成一个随机数,但它始终是相同的数字.这导致了两个问题:

While I can generate a random number, it is continuously the same number.That leads to two questions:

(1)为什么会出现这种重叠现象,我该如何解决?

(1) Why is that happing and how do I fix this?

(2)还有另一种更简单的方法来生成随机数吗?

(2) Is there another easier way to generate random numbers?

推荐答案

使用种子初始化您的生成器.在这里,我使用的是基于时间的种子.

Use a seed to initialize your generator. Here I am using a time-based seed.

#include <iostream>
#include <random>
#include <chrono>

using namespace std;

int main()
{
    unsigned seed = chrono::system_clock::now().time_since_epoch().count();
    default_random_engine generator(seed);
    normal_distribution<double> distribution(0.0, 1.0);

    cout << distribution(generator);
    return 0;
}

这篇关于C ++中来自正态分布的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:33