C:随机游走(布朗运动)程序不返回预期的理论值.为什么?

前端之家收集整理的这篇文章主要介绍了C:随机游走(布朗运动)程序不返回预期的理论值.为什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这只是基于“Feynman物理学讲座”第6-3节的实验:

In its simplest version,we imagine a “game” in which a “player”
starts at the point x=0 and at each “move” is required to take a step
either forward (toward +x) or backward (toward −x). The choice is to
be made randomly,determined,for example,by the toss of a coin.

资料来源: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?

这是我的代码

  1. #include <time.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. int main ( int argc,char *argv[] )
  6. {
  7.  
  8. int number_of_steps = 30;
  9. int repetition = 1000000;
  10. int distance = 0;
  11. int total_distance = 0;
  12. double expected_distance;
  13. int i,j;
  14.  
  15. srand(time(NULL));
  16.  
  17. for ( i = 0; i < repetition; i++ ) {
  18.  
  19. for ( j = 0; j < number_of_steps; j++) {
  20. distance += rand() & 1 ? -1 : 1;
  21. }
  22.  
  23. total_distance += abs(distance);
  24. distance = 0;
  25.  
  26. }
  27.  
  28. expected_distance = (float) total_distance / i;
  29.  
  30. printf ( "%g\n",expected_distance );
  31. return EXIT_SUCCESS;
  32. } /* ---------- end of function main ---------- */

解决方法

从您链接到的讲座中,您的理论期望基于 root mean square,这与您编码的 arithmetic mean不同.通过将算法从一个更改为另一个,the code现在可以为您提供预期的结果.
  1. for ( i = 0; i < repetition; i++ ) {
  2.  
  3. for ( j = 0; j < number_of_steps; j++) {
  4. distance += rand() & 1 ? -1 : 1;
  5. }
  6.  
  7. total_distance += distance * distance;
  8. distance = 0;
  9.  
  10. }
  11.  
  12. expected_distance = sqrt((float) total_distance / repetition);
  13.  
  14. printf ( "%g\n",expected_distance );
  15. return EXIT_SUCCESS;
  16. }

猜你在找的C&C++相关文章