我想使用N-Body
进行Hermite Algorithm
模拟,但是当我编写此代码时,我不断收到错误,说:
TypeError: 'float' object has no attribute '__getitem__'
我不知道为什么会这样,因为我的列表中的对象不是浮点数。
dt = input('dt = ')
t_end = input('t_end = ')
n = input('n= ')
t = input('t= ')
m = np.zeros(n)
r = np.zeros((n, 3))
rji = np.zeros((3))
vji = np.zeros((3))
v = np.zeros((n, 3))
a = np.zeros((n, 3))
jk = np.zeros((n, 3))
for i in range (0,n,1):
m[i] = 2
for k in range (0,3,1):
r[i,k] = 2+i
for k in range (0,3,1):
v[i,k] = 1+i
print ('m'),m,r,v
for i in range (0,n,1):
for k in range (0,3,1):
a[i,k] = jk[i,k] = 0.0
for i in range (0,n,1):
for j in range (i+1,n,1):
for k in range (0,3,1):
rji[k] = r[j,k] - r[i,k]
vji[k] = v[j,k] - v[i,k]
r2 = 0.
for k in range (0,3,1):
r2 += rji[k] * rji[k]
r3 = r2 * math.sqrt(r2)
rv = 0.
for k in range (0,3,1):
rv += rji[k] * vji[k]
rv /= r2
for k in range (0,3,1):
a[i,k] += m[j] * rji[k] / r3;
a[j,k] -= m[i] * rji[k] / r3;
jk[i,k] += m[j] * (vji[k] - 3 * rv * rji[k]) / r3;
jk[j,k] -= m[i] * (vji[k] - 3 * rv * rji[k]) / r3;
ekin = 0.
epot = 0.
for i in range (0,n,1):
for j in range (i+1,n,1):
for k in range (0,3,1):
rji[k] = r[j,k] - r[i,k] #the error coming from this line
r2=0.
for k in range (0,3,1):
r2 += rji[k] * rji[k]
print rji
r = math.sqrt(r2)
epot -= m[i] * m[j] / r
for k in range (0,3,1):
ekin += 0.5 * m[i] * v[i,k] *v[i,k]
e_in = ekin + epot
print('Initial total energy E_in = '), e_in
答案 0 :(得分:1)
我不确定这是否是您所看到的错误来源,但您在此行中缺少变量名称(所有循环的最后一行):
ekin += 0.5 * m[i] * v[i][k] *[i][k]
那应该是
ekin += 0.5 * m[i] * v[i][k] * v[i][k]
对您的代码发表评论:您正在使用二维numpy数组,因此您可以将它们编入索引,例如v[i,k]
而不是v[i][k]
。这种表示法更有效率,而且更容易阅读。