[英]Integrate coupled differential equation in Python
I have the coupled ODE, but when i run this code i get this error: TypeError: 'float' object is not subscriptable 我有耦合的ODE,但是运行此代码时出现以下错误:TypeError:“ float”对象不可下标
The error occurs on the line^ return array([-si*p[0], Here is my code: 错误发生在行^返回数组([-si * p [0],这是我的代码:
from scipy.integrate import ode
import matplotlib.pyplot as plt
import warnings
si = 1/25 #0.053
fi = 1/23 #0.05
def deriv(p,t):
return array([-si* p[0],
si * p[0] - fi * p[1],
fi * p[1] - fi * p[2],
fi * p[2] - fi * p[3],
fi * p[3] - fi * p[4],
fi * p[4] - fi * p[5],
fi * p[5] - si * p[6],
si * p[6]])
backend = 'dopri5'
t0 = 0
t1 = 2000.0
p_init = array([1, 0, 0, 0, 0, 0, 0, 0])
r = .01
solver = ode(deriv).set_integrator(backend, nsteps=1)
solver.set_initial_value(p_init, t0).set_f_params(r)
solver._integrator.iwork[2] = -1
sol = []
warnings.filterwarnings("ignore", category=UserWarning)
while solver.t < t1:
solver.integrate(t1, step=True)
sol.append([solver.t, solver.p])
warnings.resetwarnings()
sol = array(sol)
plt.plot(sol[:,0], sol[:,1], 'b.-')
plt.show()
Where is the mistake? 错误在哪里?
So, error was caused by the incorrect order of input variables in deriv
. 因此,错误是由于deriv
中输入变量的顺序错误引起的。 Here is the correct code: 这是正确的代码:
from scipy.integrate import ode
from pylab import *
import seaborn
import numpy as np
import pandas as pd
import warnings
si = 1/25 #0.053
fi = 1/23 #0.05
def deriv(t,y,r): #correct order of input variables
return np.array([-si* y[0],
si * y[0] - fi * y[1],
fi * y[1] - fi * y[2],
fi * y[2] - fi * y[3],
fi * y[3] - fi * y[4],
fi * y[4] - fi * y[5],
fi * y[5] - si * y[6],
si * y[6]])
backend = 'dopri5'
t0 = 0
t1 = 400.0
y_init = np.array([1, 0, 0, 0, 0, 0, 0, 0])
r = .01
solver = ode(deriv).set_integrator(backend, nsteps=1)
solver.set_initial_value(y_init, t0).set_f_params(r)
solver._integrator.iwork[2] = -1
ans = []
warnings.filterwarnings("ignore", category=UserWarning)
while solver.t < t1:
solver.integrate(t1, step=True)
ans.append(np.append(solver.t, solver.y)) #collect the answer on every slice of time
df = pd.DataFrame(ans)
df.columns = ['t', 'y0', 'y1','y2', 'y3', 'y4', 'y5', 'y6', 'y7'] #create DataFrame
for i in df.columns.values[1:]:
plot(df['t'], df[i]) #plotting
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.