#Math352 Project---By Yue He and Yixing Tian
#Implement the Runge-Kutta method and the taylor series-based methods for solving differential equations numerically.
#Runge-Kutta Methods is designed to imitate the Taylor series method without requiring analytic differentiation of the original differential equation.
#Taylor Series Methods described in this section does not have the utmost generality, but it is natural and capable of high precision.
#Here,we choose one question from Textbook Section 10.2,Question3,P.445. However, we choose to use order 4 to get more accurate result.
def rk4(f,x0,t0,xn):
#t(x0)=t0,dt/dx=f(x,t),and this function return the value of (xn)
#Here we choose 400, this is enough for us to get a good approximation. However, we can choose 20,50,100... to get more accurate values.
h=(xn-x0)/400
ti=t0
xi=x0
t=[t0]
x=[x0]
for i in range(400):
K1=h*f(xi,ti)
K2=h*f(xi+h/2,ti+K1/2)
K3=h*f(xi+h/2,ti+K2/2)
K4=h*f(xi+h,ti+K3)
ti+=(K1+2*K2+2*K3+K4)/6
xi+=h
t.append(ti)
x.append(xi)
return x,t
def taylor4(f1,f2,f3,f4,x0,t0,xn):
#t(x0)=t0,dt/dx=f1,df1/dx=f2,df2/dx=f3,df3/dx=f4
h=(xn-x0)/400
ti=t0
xi=x0
t=[t0]
x=[x0]
for i in range(400):
ti+=h*(f1(xi,ti)+h/2*(f2(xi,ti)+h/3*(f3(xi,ti)+h/4*f4(xi,ti))))
xi+=h
t.append(ti)
x.append(xi)
return x,t
f1=lambda x,t:-x*t**2
f2=lambda x,t:-t**2+2*x**2*t**3
f3=lambda x,t:-6*x**3*t**4+6*x*t**3
f4=lambda x,t:-18*x**2*t**4+24*x**4*t**5+6*t**3-18*x**2*t**4
RK=rk4(f1,0,2,-0.2)
TAYLOR=taylor4(f1,f2,f3,f4,0,2,-0.2)
print('the rk4 method caculate the result is',RK[1][-1])
print('the taylor4 method caculate the result is',TAYLOR[1][-1])
# Reference: Numerical Mathematics and Computing.six edition.