要生成服从标准正态分布的随机数,类似matlab中的randn函数。
C++11中引入了正态分布模板类std::normal_distribution,在头文件<random>中。
- 每次运行程序生成相同的随机序列
#include <iostream>
#include <random>
using namespace std;
int main()
{
std::default_random_engine gen;
//int seed = 3; 也可以设置一个种子
//std::default_random_engine gen(seed);
std::normal_distribution<double> dis(0,1);
std::cout << "some normal random numbers: \n";
for (int i=0; i<5; ++i)
std::cout << dis(gen) << " ";
std::cout<<endl;
for (int i=0; i<5; ++i)
std::cout << dis(gen) << " ";
std::cout << endl;
return 0;
}
- 每次运行程序产生不同的随机序列
#include <iostream>
#include <random>
#include <chrono>
using namespace std;
int main()
{
// construct a random generator engine from a time-based seed
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine gen(seed);
std::normal_distribution<double> dis(0,1);
std::cout << "some normal random numbers: \n";
for (int i=0; i<5; ++i)
std::cout << dis(gen) << " ";
std::cout<<endl;
return 0;
}
参考:https://blog.csdn.net/fengbingchun/article/details/73770856
网友评论