2011-06-20 36 views
0

這個python程序應該模擬一個物體從50米的建築物上拋出,具有一些初始速度和恆定的重力加速度。 我正在使用數組來存儲不同的組件,但是當我需要做計算的時候,我的結果矩陣並不像它應該那樣。事實上,由此產生的矩陣大部分仍然是空的。什麼可能導致這個問題?Python模擬中的邏輯錯誤

x = z = vz = vy = ax = ay = time = 0.0 
y = 50 #Initial Height: 50 meters 
vx = 25 #Initial velocity in the x direction: 25 m/s 
az = -9.8 #Constant acceleration in the z direction: -9.8 m/s^2 
deltaTime = .000001 

#Initializes a matrix with 3 columns and 1000 rows for each column: Will hold the corresponding x,y,z coordinate of the particle at time t 
positionMatrix = [[None]*1000 for x in range(3)] 

posArray = [x, y, z] 
velArray = [vx, vy, vz] 
accArray = [ax, ay, az] 
timeArray = [i*deltaTime for i in range(1000)] 

j = 1 #time increment 

for j in range (1,500): #j is the time increment 
    for i in range (1,3): #i is each component (x, y, z) 

     #x = x + vx*time + .5*ax*(time*time); #y = y + vy*time + .5*ay*(time*time); #z = z + vz*time + .5*az*(time*time) 
     positionMatrix[i][j] = posArray[i] + velArray[i] * timeArray[j] + 1/2*accArray[i] * timeArray[j] * timeArray[j] 
     print(positionMatrix) 
+0

哪裏z和VZ界定? – Nix

+0

@Nix:我修復了這個部分,但仍然沒有得到更好的結果 – kachilous

+0

個人(這不會是你的問題),如果使用它3次,我會緩存timeArray [j]。 – cwallenpoole

回答

1

您的範圍是錯誤的 - posArray索引從0到2(所以posArray [0] = x,posArray [1] = y,posArray [2] = z)。此外,您每次都打印出矩陣,因此您會看到很多無。

你也把1000行的陣中,但隨後只填寫其中的500

您應該替換代碼的最後塊:

for j in range (1000): 
    for i in range (3): 
     positionMatrix[i][j] = posArray[i] + velArray[i] * timeArray[j] + 1/2*accArray[i] * timeArray[j] * timeArray[j] 

print(positionMatrix) 
+0

謝謝,現在我想獲得一個輸出,以便我可以在Excel中繪製數據。我怎麼能改變我的代碼來做到這一點 – kachilous

+0

這是一個新問題,你應該單獨發佈。 –

+0

好的,但即使如此,通過查看數據,它仍然看起來不準確。我有很多None,我的價值非常小。這可能是我的時間陣列嗎? – kachilous

1

我不確定您有任何問題嗎?你如何評判失敗?是否因爲你每次打印positionMatrix?

它看起來沒有什麼,因爲你打印出3k無每次迭代。從改變你的代碼行:

print(positionMatrix) 

print(positionMatrix[i][j]) 

我做了

cnt=0 
for j in range (1,500): #j is the time increment 
    for i in range (1,3): #i is each component (x, y, z) 
    positionMatrix[i][j] = posArray[i] + velArray[i] * timeArray[j] + 1/2*accArray[i] * timeArray[j] * timeArray[j] 
    if(positionMatrix[i][j] == None): 
     cnt +=1 
print 'none count' , cnt 

結果是

無計0

所以你可以看到每一行都被設置爲某種東西。至少你正在處理的,在0開始你的範圍(不指定1)。

for j in range (500): #j is the time increment 
    for i in range (3): #i is each component (x, y, z) 
+0

我也注意到了這一點。我在想也許他的問題不是矩陣是空的,而只是他被輸出的大量困惑。 – jhocking

+0

你的意思是:print(positionMatrix [i] [j])? – kachilous

0

我不知道這是不是在你的代碼的唯一,甚至最重要的問題,但你從1開始的範圍這意味着你通過數組的第一個元素,索引0從不循環。