Bluemo's Brain

Search

Search IconIcon to open search

オイラー法

Last updated Unknown Edit Source

    eular.py

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    
    import matplotlib.pyplot as plt
    import math
    
    # 微分方程式の関数
    # xがこの値の場合に、
    def dxdt(x, t):
        return math.sin(t)
    
    # オイラー法
    def euler(x0, t0, tn, h):
        x = x0
        t = t0
        n = int((tn - t0) / h)
        X = []
        T = []
        # 漸化式を計算
        for i in range(n):
            x += dxdt(x, t) * h
            X.append(x)
            t = t0 + i * h
            T.append(t)
        return X, T
    
    #lim h->0のさまざまな値でためしたsin wave
    #細かくなるほど良い近似に
    X, T = euler(-2, 0, 50, 1)
    plt.plot(T,X)
    X, T = euler(-2, 0, 50, 0.5)
    plt.plot(T,X)
    X, T = euler(-2, 0, 50, 0.01)
    plt.plot(T,X)
    plt.show()