我正在使用 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))
你觉得我能怎么解决这个问题?
非常感谢。