1

我正在使用 Python 3。下面的代码尝试在 3 维中模拟随机游走的 N 步。在每一步,随机选择一个方向(北、南、东、西、上、下),每个方向的概率为 1/6,并在该方向上采取大小为 1 的步长。然后打印新位置。起始位置是原点 (0,0)。

即使没有错误消息,代码也不起作用。我们应该在 x、y 或 z 中只移动一步。但是,在输出中,我看到有时我根本不动,或者有时我朝多个方向移动。

这是我的代码:

import random

N = 30

n = random.random() 

x = 0
y = 0
z = 0
count = 0

while count <= N:

    if n < 1/6:
        x = x + 1          
        n = random.random()
    if n >= 1/6 and n < 2/6:
        y = y + 1           
        n = random.random() 
    if n >= 2/6 and n < 3/6:
        z = z + 1           
        n = random.random() 
    if n >= 3/6 and n < 4/6:
        x = x - 1           
        n = random.random() 
    if n >= 4/6 and n < 5/6:
        y = y - 1          
        n = random.random() 
    if n >= 5/6:
        z = z - 1          
        n = random.random()

    print("(%d,%d,%d)" % (x,y,z))
    count = count + 1

print("squared distance = %d" % (x*x + y*y + z*z))

你觉得我能怎么解决这个问题?

非常感谢。

4

3 回答 3

3

你应该使用elif而不是这么多的ifs。每次评估 if 时,n 的值都会发生变化,然后可能符合下一个 if 的条件。

于 2017-09-24T18:36:11.203 回答
2

您不仅应该使用elif,甚至为了提高性能,而且您不需要n = random.random()循环中的多个语句——一个就可以了:

import random

N = 30

x = 0
y = 0
z = 0

for _ in range(N):

    n = random.random()

    if n < 1/6:
        x += 1
    elif 1/6 <= n < 2/6:
        y += 1
    elif 2/6 <= n < 3/6:
        z += 1
    elif 3/6 <= n < 4/6:
        x -= 1
    elif 4/6 <= n < 5/6:
        y -= 1
    elif n >= 5/6:
        z -= 1

    print(f"({x},{y},{z})")  # python 3.6ism

print("squared distance = {}".format(x*x + y*y + z*z))
于 2017-09-24T18:44:03.117 回答
1

无论您使用的是哪个版本的 Python,您都需要实现 @cdlane 提供的答案。

如果您使用的是 Python 2.X,那么您的另一个问题是 Python 将您的数字解释为ints. 要解决这个问题,您需要添加.到分母,即

if n < 1/6.:

代替

if n < 1/6:

1/6和其他分数被解释为ints- 您可以通过键入print 1/6which will give you0或打印实际类型来自行检查print type(1/6)- 这将 yield <type 'int'>

因此,当您运行程序时,您的所有ns 将仅满足最后一个条件(所有都将大于 0)。

于 2017-09-24T18:48:29.650 回答