我遇到一個問題,我的代碼映射在3D空間中隨機遊走。此代碼的目的是模擬3維隨機遊走的N個步驟。在每個步驟中,選擇一個隨機方向(北,南,東,西,上,下),並在該方向上採用大小爲1的步驟。這是我的代碼:重複如果語句
import random # this helps us generate random numbers
N = 30 # number of steps
n = random.random() # generate a random number
x = 0
y = 0
z = 0
count = 0
while count <= N:
if n < 1/6:
x = x + 1 # move east
n = random.random() # generate a new random number
if n >= 1/6 and n < 2/6:
y = y + 1 # move north
n = random.random() # generate a new random number
if n >= 2/6 and n < 3/6:
z = z + 1 # move up
n = random.random() # generate a new random number
if n >= 3/6 and n < 4/6:
x = x - 1 # move west
n = random.random() # generate a new random number
if n >= 4/6 and n < 5/6:
y = y - 1 # move south
n = random.random() # generate a new random number
if n >= 5/6:
z = z - 1 # move down
n = random.random() # generate a new random number
print("(%d,%d,%d)" % (x,y,z))
count = count + 1
print("squared distance = %d" % (x*x + y*y + z*z))
問題是我在每次迭代之間獲得的不止一個步驟。我添加了評論,顯示了迭代之間的差異。
以下是輸出的第10行:
(0,-1,0) #1 step
(0,-2,0) #1 step
(1,-3,1) #4 steps
(1,-4,1) #1 step
(1,-3,1) #1 step
(1,-2,1) #1 step
(2,-2,0) #2 steps
(2,-2,0) #0 steps
(2,-2,0) #0 steps
(2,-1,0) #1 step