I want to solve the following system using the numerical method Runge Kutta of order 4:
y'=-xy x'=-x+sin(t)
with initial conditions x(0)=0.75 and y(0)=0
Using RungeKutta of order code 4 I tried this:
def GlucoseTT(x, t, params):
a = params["a"]
b= params["b"]
c= params["c"]
xdot= np.array([a*x[0]-b*x[1], -c*x[0]+np.sin(t)])
return xdot
def RK4(f, x0, t0, tf, dt):
t=np.arange(t0,tf,dt)
nt=t.size
nx=x0.size
x=np.zeros((nx,nt))
x[:,0]=x0
for k in range(nt-1):
k1= dt*f(t[k], x[:,k])
k2= dt*f(t[k]+dt/2, x[:,k]+k1/2)
k3= dt*f(t[k]+dt/2, x[:,k]+k2/2)
k4= dt*f(t[k]+dt, x[:,k]+k3)
dx=(k1+2*k2+2*k3+k4)/6
x[:,k+1]=x[:,k]+dx
return x, t
#Define Problem
params = {"a":1, "b":1, "c":1}
f= lambda t, x : GlucoseTT(x, t, params)
x0= np.array([0.75,0])
#Solve ODE
t0=0
tf= 100
dt= 0.1
x,t =RK4(f, x0, t0, tf, dt)
plt.plot(t,x[0,:],"r")
I dont' know if this code works....
Not an answer, but the solution of the equations, so that you can compare:
X = C e^-t + (sin(t) - cos(t)) / 2
Y = D e^-t - C t e^-t + cos(t) / 2
The initial conditions give the system
0.75 = C - 0.5
0 = D + 0.5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.