视觉 正态分布的每个模拟都是相同的 (C++)

visual Each simulation of normal distribution is the same (C++)

本文关键字:C++ 正态分布 模拟 视觉      更新时间:2023-10-16

我编写了一个代码来模拟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 中运行。

您每次都从同一种子构造default_random_engine: 由于您没有给它一个种子来构造,它只是使用默认值,每次运行都相同,因此每次运行都会得到相同的"随机"数字。 http://www.cplusplus.com/reference/random/linear_congruential_engine/linear_congruential_engine/

使用random_device为生成器设定种子。

std::default_random_engine dre(std::random_device()()); 

尝试:

std::random_device mch;
std::default_random_engine generator(mch());
std::normal_distribution<double> distribution(0.0, 1.0);