2014-02-24 67 views
-1

我不明白爲什麼我得到這個索引超出界限的錯誤。我已經完成了這些索引值的測試打印,並且它們正確地打印出來。有人可以解釋我的陣列正在被重組的位置嗎?索引超出界限錯誤:動畫/模擬

class Particle: 

    def __init__(self,fourvector = [1.0,1.0,1.0,-1.0], 
       origin=(0,0)): 
     self.mass = 2.5  # Mass in kg 
     self.fourvector = np.asarray(fourvector,dtype='float') 
     self.Vx_init = self.fourvector[2] 
     self.x_init = self.fourvector[0] 
     self.y_init = self.fourvector[1] 
     self.Vy_init = self.fourvector[3] 
     self.time_passed = 0 
     self.origin = origin 
     print fourvector[0] 
     print fourvector[2] 

    def position(self): 
     x0 = self.origin[0] 
     x1 = self.fourvector[0] 
     Vx = self.fourvector[2] 
     y0 = self.origin[1] 
     y1 = self.fourvector[1] 
     Vy = self.fourvector[3] 
     x = x0 + x1 * Vx 
     y = x0 + y1 * Vy 

     return (x,y) 

    def derivs(self,fourvector): 
     '''derivative computation setup''' 
     x_pos = fourvector[0] 
     y_pos = fourvector[1] 
     dydx = np.zeros_like(fourvector) 
     dydx[0] = fourvector[2] #x-comp of velocity 
     dydx[1] = (-x_pos)/((x_pos)**2 + (y_pos)**2)**1.5 
     dydx[2] = fourvector[3] #y-comp of velocity 
     dydx[3] = (-y_pos)/((x_pos)**2 + (y_pos)**2)**1.5 
     return dydx 

    def time_step(self,dt): 
     '''Time progression and state fourvector update''' 
     self.fourvector = integrate.odeint(self.derivs,0,dt) 
     self.time_passed += dt 


body = Particle([1.0,1.0,1.0,2.0]) #Object of Particle created. 
dt = 1./30 

fig = plt.figure() 
ax = fig.add_subplot(111,aspect='equal',autoscale_on=False,xlim=(-3,3),ylim=(-3,3)) 
ax.grid() 

line, = ax.plot([],[],'o-',lw=2) 
time_text = ax.text(0.02,0.95,'',transform=ax.transAxes) 

def init(): 
    line.set_data([],[]) 
    time_text.set_text('') 
    return line, time_text 

def animate(i): 
    global body, dt 
    body.time_step(dt) 
    line.set_data(*body.position()) 
    time_text.set_text('time = %.1f' %body.time_passed) 
    return line, time_text 

from time import time 
t0 = time() 
animate(0) 
t1 = time() 
interval = 1000*dt - (t1 - t0) 

ani = animation.FuncAnimation(fig, animate, frames = 300, 
           interval = interval, blit=True, init_func=init) 
plt.show() 

錯誤回溯:

bash-3.2$ python MoreCrap.py 
1.0 
1.0 
Traceback (most recent call last): 
    File "MoreCrap.py", line 80, in <module> 
    animate(0) 
    File "MoreCrap.py", line 74, in animate 
    line.set_data(*body.position()) 
    File "MoreCrap.py", line 26, in position 
    Vx = self.fourvector[2] 
IndexError: index out of bounds 
+0

投票關閉?爲什麼?我看不到我的索引在哪裏重新排列,看起來像是一個簡單的編程問題... – Matt

回答

1

您的來電integrate.odeint是錯誤的。看看手冊,如果它真的做你的想法。

在任何情況下,fourvector有對它的調用和值[[0.]]調用它前後值[1. 1. 1. 2.],所以它不包含指數[2]任何價值。

odeint的手冊頁是here

+0

感謝您指出'integrate.odeint'問題。儘管如此,我仍然試圖圍繞從'[1 1 1 2]'到'[[0]]'的'fourvector'的方向前進。 – Matt