正态分布的每次模拟都是一样的(C++) [英] Each simulation of normal distribution is the same (C++)
问题描述
我写了一段代码来模拟 C++ 中的正态分布.但每次似乎结果都是一样的.我的问题是这种现象的原因是什么以及如何解决?我用 Python 从来没有这个问题.任何参考都非常感谢.
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;
}
我的代码在 Visual C++ 2010 中运行.
My code runs in visual C++ 2010.
推荐答案
你每次都从同一个种子构建 default_random_engine
:因为你没有给它一个种子来构建,它只是使用默认值,每次运行都相同,因此每次运行都会得到相同的随机"数字.http://www.cplusplus.com/reference/random/linear_congruential_engine/linear_congruential_engine/一个>
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/
使用 random_device 为生成器设置种子.
Use random_device to seed the generator.
std::default_random_engine dre(std::random_device()());
这篇关于正态分布的每次模拟都是一样的(C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!