【问题标题】:Each simulation of normal distribution is the same (C++)正态分布的每次模拟都是一样的(C++)
【发布时间】:2014-04-07 19:58:25
【问题描述】:

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

【问题讨论】:

  • 请注意格式。这就是预览面板的用途。

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


【解决方案1】:

你每次都从同一个种子构造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()()); 

【讨论】:

    【解决方案2】:

    试试:

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

    【讨论】:

    • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    猜你喜欢
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多