类型错误:'float'对象没有属性'__getitem__' Python NBody 模拟



我想用Hermite Algorithm模拟N-Body,但当我写这段代码时,我一直收到一个错误,上面写着:

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

我不确定这是否是您看到的错误源,但您在这一行(所有循环的最后一行)中缺少一个变量名:

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

相关内容

  • 没有找到相关文章

最新更新