C++:利用随机函数,根据高尔顿原理产生正态分布。(打开Excel,利用图表现的向导look)

来源:互联网 发布:阿里云 安卓 编辑:程序博客网 时间:2024/05/17 03:50

#include <iostream>
#include <time.h>
#include <fstream>

using namespace std;
//Golton板仿真,将随机数加工为正态分布

int Golton(int theMidPlace,int theLevel)
{
 if ((rand()/10%2)==1)
 {
  if (rand()%2==1)
  {
   theMidPlace++;
  }
  else
   theMidPlace--;
 }
 for (int i = 0;i<theLevel;i++)
 {
  
  if (rand()/4%2==1)
  {
   theMidPlace++;
  }
  else
   theMidPlace--;
 }
 return theMidPlace;
}

//主函数实现正态分布,并把数据存储在Excel

void main()
{
 long x,midplace,level,count[101];
 time_t t;
 srand((unsigned)time(&t));

 ofstream fp;
 fp.open("d://Golton.xls");
    //把数据存储在生成的Excel表格里
 cout<<"输入初值的位置";
 cin>>midplace;
 cout<<endl<<"输入Golten的层数";
 cin>>level;
    for(int j = 0;j<101;j++)
 {
  count[j]=0;
 }
 for(long k =0;k<1000000;k++)
 {
  x=Golton(midplace,level);
  if(x>=0&&x<=100)
  count[x]++;
  else continue;
 }
 for(int i = 0;i<101;i++)
 {
 
  fp<<i<<"/t";
 }
 fp<<endl;
 for(int m = 0; m<101;m++)//把数据读入Excel表格
 {

  
  fp<<count[m]<<"/t";
  
 }
 fp.close();//关闭文件
 
  
 
}

原创粉丝点击