问题
I write a code to simulate a normal distribution in C++. But each time it seems the result is the same. My question is what't the reason of this phenomenon and How to fix it? I never have this problem with Python. Any references are very appreciated.
// 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;
}
My code runs in visual C++ 2010.
回答1:
You're constructing the default_random_engine
from the same seed every time: Since you aren't giving it a seed to construct with, it simply uses the default, which is the same every run, so you get the same "random" numbers each run. http://www.cplusplus.com/reference/random/linear_congruential_engine/linear_congruential_engine/
Use random_device to seed the generator.
std::default_random_engine dre(std::random_device()());
回答2:
Try:
std::random_device mch;
std::default_random_engine generator(mch());
std::normal_distribution<double> distribution(0.0, 1.0);
来源:https://stackoverflow.com/questions/22921853/each-simulation-of-normal-distribution-is-the-same-c