一名醉汉每次在前后左右四个方向中随机选择一个方向走一米,请问走了n步之后该醉汉离出发位置有多远?
注:由于每次走的路径都不相同,因此每次走了n步后离出发位置的距离可能不相同,
因此需要模拟m次,然后求出这m次的平均值。
C++实现如下:
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
using namespace std;
int main() {
int m, n, i, j, x, k, y, fourDirections;
double d, s;
x = 0, y = 0, d = 0, s = 0;
cout << "input simulation times (m): " << endl;
cin >> m;
cout << "input the number of steps: " << endl;
cin >> n;
srand(time(NULL));
for (k = 1; k <= n; k++) {
x = 0, y = 0, s = 0;
for (j = 1; j <= m; j++) {
x = 0, y = 0;
for (i = 1; i <= k; i++) {
fourDirections = rand() * 4 / (RAND_MAX + 1);
switch (fourDirections) {
case 0:
x += 1;
break;
case 1:
x -= 1;
break;
case 2:
y += 1;
break;
case 3:
y -= 1;
break;
}
}
d = sqrt(x * x + y * y);
s += d;
}
cout << s / m << endl;
}
return 0;
}
利用matlab绘制运行结果:
散点图
思考背后的概率论逻辑