16

用C++模拟蚊子的运动来检验概率论内容

 4 years ago
source link: http://www.cnblogs.com/chanji/p/12818554.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

背景:在一个很大的方形透明容器内,从某个位置放入适量的蚊子,等待几分钟后观察蚊子的分布.

#include <iostream>

#include <cstdlib>

#include <ctime>

#define random(a,b) (rand() % (b-a+1))+ a

using namespace std;

int main()

{

srand((int)time(0));

int x;

int a[20001] = {0}; //哈希数组,用于记录蚊子的位置

int temp;

for(int i = 0;i < 1000;++i) { //循环1000次代表放进1000只蚊子

x = 0; //x坐标为0,代表蚊子从容器中间放入

for(int j = 0;j < 20000;++j) { //循环20000次代表蚊子运动20000次

temp = random(0,200) - 100; //随机蚊子运动一次的距离,在-100到100之间

x += temp;

while(x < -10000 || x > 10000) { //若蚊子运动超出边界,则重新随机,直到蚊子的位置不超出边界

x -= temp;

temp = random(0,200) - 100;

x += temp;

}

}

a[x+10000]++; //用哈希标记蚊子运动之后的x坐标

}

int b[80] = {0}; //以下是把蚊子的位置按照每250一个区间分80个区间统计输出

for(int i = 0;i < 80;++i) {

for(int j = i * 250;j < (i+1) * 250;++j) {

if(a[j] != 0) {

b[i]++;

}

}

cout << i + 1 << " " << b[i] << endl;

}

/*for(int i = 0;i <= 20000;++i) {

cout << i + 1 << " " << a[i] << endl;

}*/

return 0;

}

当蚊子移动20000次的时候,得到的图像是不符合正态分布的:

NF3Afae.png!web

当蚊子移动2000次的时候,得到的图像符合正态分布:

V7rYF3b.png!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK