gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:21:19 26 4
gpt4 key购买 nike

这只是基于《费曼物理讲义》第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 左右的理论值?

这是我的代码:

#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 ---------- */

最佳答案

根据您链接的讲座,您的理论期望基于 root mean square ,这不同于 arithmetic mean ,这是您编码的内容。通过将算法从一种更改为另一种,the code现在给你预期的结果。

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;
}

关于C:随机游走(布朗运动)程序没有返回预期的理论值。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26245828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com