精細積分python實現

精細積分

《計算機科學計算》張宏偉 第二版 p258

計算dx(t)/dt=Ax(t)的近似解,初值條件爲x(t0)=x0

import numpy as np

N = 20  # 步長h細分爲2^N


def precise_integration(A, x0, h, t0, t1):
    """
    計算dx(t)/dt=Ax(t)的近似解,初值條件爲x(t0)=x0
    :param A: 矩陣A
    :param x0: 初值x0
    :param h: 時間步長h
    :param t0: 區間左端點t0
    :param t1: 區間右端點t1
    :return: 近似解x
    """
    n = len(x0)  # 未知數個數
    m = int((t1 - t0) / h)
    I = np.eye(N=n)
    x = np.mat(np.zeros((n, m + 1)))
    x[:, 0] = x0.reshape(3, 1)  # 初值
    dt = float(h) / pow(2, N)  # 精細化步長
    At = A * dt
    BigT = At * (I + At * (I + At / 3.0 * (I + At / 4.0)) / 2.0)
    for i in range(N):
        BigT = 2 * BigT + np.dot(BigT, BigT)
    BigT += I
    for i in range(m):
        x[:, i + 1] = np.dot(BigT, x[:, i])
    return x

def evaluate(t):
    """
    計算真實值
    :param t:自變量t
    :return:x(t)
    """
    return -1 / 6.0 * np.array([-1 + 3 * np.exp(2 * t) - 8 * np.exp(3 * t), -5 + 3 * np.exp(2 * t) - 4 * np.exp(3 * t),
                                -2 - 4 * np.exp(3 * t)])


if __name__ == "__main__":
    # 已知A,x0
    A = np.mat([[3, -1, 1],
                [2, 0, -1],
                [1, -1, 2]])
    x0 = np.array([1, 1, 1])

    # 步長,區間端點
    h = 0.2
    t0 = 0
    t1 = 1
    
    X = precise_integration(A, x0, h, t0, t1)
    print(X)
    x1 = evaluate(1)
    print(x1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章