vxs*_*122 6 c random probability
这只是基于"Feynman物理学讲座"第6-3节的实验:
在最简单的版本中,我们想象一个"游戏",其中"玩家"从点x = 0开始,并且在每次"移动"时需要向前(向+ x)或向后(向-x)迈出一步.选择是随机进行的,例如通过掷硬币来确定.
资料来源:http://www.feynmanlectures.caltech.edu/I_06.html#Ch6-S3
我的目标是计算距离说明点的预期距离.所以,我想每一步都等于一个距离单位.我写了一个简单的C程序来模拟30个随机步骤,然后计算起点的最终距离.重复一百万次,程序平均距离以获得预期距离.
理论上,预期距离应该是步数的平方根.那应该是sqrt(30)= 5.48.
但是,该程序运行几次并保持返回接近4.33的值(更确切地说,4.33461,4.33453和4.34045).为什么它甚至不接近理论值约5.48?
这是我的代码:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main ( int argc, char *argv[] )
{
int number_of_steps = 30;
int repetition = 1000000;
int distance = 0;
int total_distance = 0;
double expected_distance;
int i, j;
srand(time(NULL));
for ( i = 0; i < repetition; i++ ) {
for ( j = 0; j < number_of_steps; j++) {
distance += rand() & 1 ? -1 : 1;
}
total_distance += abs(distance);
distance = 0;
}
expected_distance = (float) total_distance / i;
printf ( "%g\n", expected_distance );
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */
Run Code Online (Sandbox Code Playgroud)
从您链接到讲座中,你的理论预期是基于均方根,这是从不同的算术平均值,这是你的编码是什么.通过将算法从一个更改为另一个,代码现在可以为您提供预期的结果.
for ( i = 0; i < repetition; i++ ) {
for ( j = 0; j < number_of_steps; j++) {
distance += rand() & 1 ? -1 : 1;
}
total_distance += distance * distance;
distance = 0;
}
expected_distance = sqrt((float) total_distance / repetition);
printf ( "%g\n", expected_distance );
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)