使用泰勒级数方法逼近 ODE 解

计算科学 数字
2021-12-05 02:20:57

这是我第一次在这里发帖,如有错误请见谅。

我试图根据泰勒级数绘制两个 ODE 求解器之间的区别:

  • 一阶准确: x(t0+h)=x(t0)+hx(t0)
  • 二阶准确: x(t0+h)=x(t0)+hx(t0)+h22x(t0)

常微分方程:x'= -x + e^-t x0 = 0;t0 = 0 x'' = x - 2e^-t

由于某种原因,真正的解决方案和一阶和二阶近似是相同的。有任何想法吗?

from math import exp
from numpy import arange
from numpy import zeros
from matplotlib import pyplot as plt

def f(t,x):
    dx = -x + exp(-t)
    return dx

def df(t,x):
    df = x - 2*exp(-t)
    return df

def real(h):
    t = 0
    xk_list = []
    tk_list = []
    def func(t):
        x = t*exp(-t)
        return x

    while(True):
        xk_list.append(func(t))
        tk_list.append(t)
        t += h
        if (t > 3.0):
            return tk_list, xk_list

def forward_euler_1(x0, t0, h):
    xk = x0
    tk = t0
    tk_list = []
    xk_list = []
    counter = 0
    while(True):
        xk1 = xk + h*f(tk,xk)
        xk_list.append(xk)
        tk_list.append(tk)
        if(tk > 3.0):
            print(counter,tk)
            return tk_list, xk_list
        xk = xk1
        tk = tk + h
        counter += 1

def forward_euler_2(x0,t0,h):
    xk = x0
    tk = t0
    tk_list = []
    xk_list = []
    counter = 0 

    while(True):
        xk1 = xk + h*f(tk, xk) + (h**2)/2*df(tk, xk)
        xk_list.append(xk1)
        tk_list.append(tk)    
        if(tk > 3.0):
            print(counter,tk)
            return tk_list, xk_list        
        xk = xk1
        tk = tk + h
        counter += 1

x, y = forward_euler_1(0.0, 0.0,0.001)
x2, y2 = forward_euler_2(0.0, 0.0, 0.001)
x3, y3 = real(0.001)

plt.plot(x,y)
plt.plot(x2,y2,'--')
plt.plot(x3, y3)
plt.show()       
1个回答

代码没有任何问题,我只是使用了太高的 h 分辨率,如果将时间离散化为 0.1,你会看到我期望看到的。