无法按预期递增整数

Unable to increment integers as expected

我正在观看有关 python (https://www.youtube.com/watch?v=BfS2H1y6tzQ) 的 Monte Carlo 问题的简短 youtube 视频教程,但代码无法正常工作。目标是看看我需要坐多少次交通工具才能回家,考虑到如果距离大于 4,你就坐交通工具。

所以我认为问题是每次调用 random_walk 时,x,y 变量都被重置为零,因此距离永远不会始终在 0-1 范围内并且不会递增预期的。

import random


def random_walk(n):
    x, y = 0, 0
    for i in range(n):
        (dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
        x += dx
        y += dy
    return (x, y)

number_of_walks = 10000
no_transport = 0

for walk_length in range(1, 31):
    for i in range(number_of_walks):
        (x, y) = random_walk(walk_length)
        distance = abs(x) + abs(y)

        if distance <= 4:
            no_transport += 1

    transported_percentage = float(no_transport) / number_of_walks
    print("Walk Size = ", walk_length, " / % transported = ", 100 * transported_percentage)

我希望结果能显示 % 我必须把车送回家的次数,相反,我得到的数字不准确,例如 100, 200, 300%。视频教程会不会有错误的代码?

您需要在主循环中重置 no_transport,因为它是在您的所有测试中累积的,而不是针对每个步行长度。

for walk_length in range(1, 31):
    no_transport = 0

此外,百分比计算的是 no_transport 步行的次数,而不是运输步行的百分比:这是运输的百分比。

transported_percentage = (number_of_walks - float(no_transport)) / number_of_walks