2011-06-20 37 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从不循环。