c++ - C++中正态分布的随机数

标签 c++ c++17

作为 C++ 的完全初学者,我想从正态分布中生成一个随机数。

使用以下代码(源自 post ),我能够这样做:

#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;
}

由于代码相当复杂(在我看来),我认为可能有一个更直接的解决方案:
#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;
}

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

(1) 为什么会这样,我该如何解决?

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

最佳答案

使用种子初始化您的 generator .这里我使用的是基于时间的种子。

#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++ - C++中正态分布的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60721093/

相关文章:

c++ - 有没有一种方法可以在不使用两个 for 循环的情况下迭代两个容器

c++ - 如何在 C++ 包扩展中包含多行或语句?

c++ - 如何从未知类型的变量访问嵌套类型?

c++ - 如何在不使用类次的情况下找到 TMax

c++ - 函数的模板推导如何在 C++ 中工作?

c++ - 在编译时从可能类型的集合中获取整数?

c++ - 为什么 sizeof(std::variant) 与具有相同成员的结构的大小相同?

c++ - C++ 中的默认引用参数

c++ - 在关闭文件时获取段错误

c++ - Valgrind 在为字符串赋值时报告内存泄漏