我无法弄清楚为什么我的这个索引超出了界限错误。我已经在这些索引上完成了值的测试打印,并且它们正确打印出来。有人可以解释我的阵列正在重组的位置吗?
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 :(得分:1)
您对integrate.odeint
的来电是错误的。如果它真的符合您的想法,请查看手册。
在任何情况下,fourvector
在调用它之前都有值[1. 1. 1. 2.]
,在调用它之后值为[[0.]]
,所以它不包含任何带索引{{1}的值1}}。
odeint的联机帮助页是here。