-2

我想使用 进行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
4

1 回答 1

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]. 这种表示法效率更高,也更容易阅读。

于 2014-10-13T07:03:21.840 回答