问题描述
我正在尝试使用python scipy模块的RK45 / RK23求解器。用它来解决简单的ODE并没有给我正确的结果。当我手动为Runge Kutta 4阶编码时,它可以完美工作,模块中的odeint求解器也可以,但是RK23 / RK45不能。如果有人可以帮助我解决问题,那将是有帮助的。到目前为止,我仅实现了简单的ODE
dydt = -K *(y ^ 2)
代码:
import numpy as np
from scipy.integrate import solve_ivp,RK45,odeint
import matplotlib.pyplot as plt
# function model fun(y,t)
def model(y,t):
k = 0.3
dydt = -k*(y**2)
return dydt
# intial condition
y0 = np.array([0.5])
y = np.zeros(100)
t = np.linspace(0,20)
t_span = [0,20]
#RK45 implementation
yr = solve_ivp(fun=model,t_span=t_span,y0=y,t_eval=t,method=RK45)
##odeint solver
yy = odeint(func=model,y0=y0,t=t)
##manual implementation
t1 = 0
h = 0.05
y = np.zeros(21)
y[0]=y0;
i=0
k=0.3
##Runge Kutta 4th order implementation
while (t1<1.):
m1 = -k*(y[i]**2)
y1 = y[i]+ m1*h/2
m2 = -k*(y1**2)
y2 = y1 + m2*h/2
m3 = -k*(y2**2)
y3 = y2 + m3*h/2
m4 = -k*(y3**2)
i=i+1
y[i] = y[i-1] + (m1 + 2*m2 + 2*m3 + m4)/6
t1 = t1 + h
#plotting
t2 = np.linspace(0,20,num=21)
plt.plot(t2,y,'r-',label='RK4')
plt.plot(t,yy,'b--',label='odeint')
#plt.plot(t2,yr.y[0],'g:',label='RK45')
plt.xlabel('time')
plt.ylabel('y(t)')
plt.legend()
plt.show()
我找不到我在哪里犯错
解决方法
好的,我已经找到了解决方案。 RK45要求函数定义必须像fun(t,y)一样,而odeint要求函数定义必须像func(y,t)一样,因为给它们相同的函数会导致不同的结果。