用C++模擬蚊子的運動來檢驗概率論內容

用C++模擬蚊子的運動來檢驗概率論內容

背景:在一個很大的方形透明容器內,從某個位置放入適量的蚊子,等待幾分鐘後觀察蚊子的分佈.

include

include

include

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次的時候,得到的圖像是不符合正態分佈的:

當蚊子移動2000次的時候,得到的圖像符合正態分佈:

原文地址https://www.cnblogs.com/chanji/p/12818554.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章