我编写了一个代码来模拟C ++中的正态分布。但每次看起来结果都是一样的。我的问题是这种现象的原因是什么以及如何解决?我从未遇到过Python这个问题。任何参考文献都非常感谢。
// Simulation.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include<random>
void main(){
// create default engine as source of randomness
// The maxtime we do expriements is 10000
// Record to the sum of the maxtimes sample
std::default_random_engine dre;
const int maxtimes = 10000;
double sum = 0.0 ;
// Generate the normal distribution witn mean 0 and variaiton 1.
std::normal_distribution<double> distribution(0.0, 1.0);
// Output the result and Record their sum.
for( int i=0; i<maxtimes; ++i)
{
double x = distribution(dre);
std::cout << x << ":";
sum +=x;
x =0.0;
}
std::cout<<std::endl;
std::cout <<" The average sum is: " << sum/10000 <<std::endl;
}
我的代码在visual C ++ 2010中运行。
答案 0 :(得分:3)
你每次都从同一个种子构建default_random_engine
:既然你没有给它构建一个种子,它只使用默认值,每次运行都是一样的,所以你得到同样的&#34;随机&#34;每个运行的数字。 http://www.cplusplus.com/reference/random/linear_congruential_engine/linear_congruential_engine/
使用random_device为生成器播种。
std::default_random_engine dre(std::random_device()());
答案 1 :(得分:0)
尝试:
std::random_device mch;
std::default_random_engine generator(mch());
std::normal_distribution<double> distribution(0.0, 1.0);