我目前正在使用Python来解决使用rk方法的函数。 r8_rkf45是一个文件,有助于绘制函数(http://people.sc.fsu.edu/~jburkardt/py_src/rkf45/rkf45.py)。
import numpy as np
import matplotlib.pyplot as plt
from numpy import zeros, linspace, exp, sqrt
from rkf45 import *
from r8_rkf45 import *
def rungekutta(ode2, x0, t, n):
n = 200
z = zeros(n)
a = zeros(n)
f = ode2
neqn = 1
abserr = sqrt(finfo(double).eps)
relerr = sqrt(finfo(double).eps)
flag = 1
t_start = 0.0
t_stop = 10.0
t_out = t = 0.0
y = np.array([0.0])
yp[t, y] = ode2[t, y]
for i_step in xrange(0, n - 1):
t = ((n - i_step + 1) * t_start + (i_step - 1) * t_stop) / (n)
t_out = ((n - i_step) * t_start + (i_step) * t_stop) / (n)
y, yp, t = r8_rkf45(ode2, neqn, y, yp, t, t_out, relerr, abserr, flag)
z[i_step - 1] = t
a[i_step - 1] = y
def ode2(x0, t):
alpha = -1
xp = -alpha * x0
return xp
def main():
n = 200
c, b = (0.0, 10.0)
x0 = 1.0
t = linspace(c, b, n)
y = np.array([0.0])
yp[t, y] = ode2[t, y]
plt.plot()
result_rungekutta = rungekutta(yp, x0, t, n)
plt.plot(t, result_rungekutta, "r")
plt.xlabel(t)
plt.ylabel(xp)
plt.legend("Runge-Kutta")
plt.show()
if __name__ == "__main__":
main()
但我仍然得到一个追溯:
Traceback (most recent call last):
File "C:/Python27/idea.py", line 50, in <module>
main()
File "C:/Python27/idea.py", line 40, in main
yp [t,y]= ode2 [t, y]
TypeError: 'function' object has no attribute '__getitem__'
我做错了什么?
答案 0 :(得分:3)
ode2
是一个函数,而不是一个列表(或其他具有可通过索引访问的成员的对象)。试试,yp [t,y]= ode2(t, y)
答案 1 :(得分:1)
您需要使用()
调用函数:
yp [t,y]= ode2(t, y)