醉汉随机行走问题 C++实现

一名醉汉每次在前后左右四个方向中随机选择一个方向走一米,请问走了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绘制运行结果:

散点图
醉汉问题散点图
思考背后的概率论逻辑

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值