c++ - 每次模拟正态分布都是一样的(C++)

标签 c++ visual-c++ simulation random

我用 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()()); 

关于c++ - 每次模拟正态分布都是一样的(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921853/

相关文章:

animation - 在 gnuplot 中制作电影的更快方法

Excel VBA 中的数组。在某些时候,它会放置 NA 而不是 value

c++ - 自定义异常中的损坏消息

c++ - 为什么 "a->content"给我一个地址而不是一个值?

neural-network - 神经网络真的可以学习吗?

c - FreeLibrary 在 VC14 上泄漏,但在 VC9 上没有泄漏

visual-c++ - 是否禁止重新分发 C++ 2008 Redistributable Package?

c++ - 运行时使用的自定义调试 printf

c# - 将 C++ 方法转换为 C# 时遇到问题

c++ - 手动对象构造函数调用