Bluemo's Brain

Search

Search IconIcon to open search

複数関数受けれるオイラー法のコード

Last updated Unknown Edit Source

     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
    33
    34
    35
    
    import matplotlib.pyplot as plt
    import math
    import numpy as np
    
    # 微分方程式の関数
    def dxdt(x, t):
        gradients = []
        for i in range(len(x)):
            gradients.append(1)
        return gradients
    
    # オイラー法
    def euler(num, x0, t0, tn, h):
        x = x0.copy()
        t = t0.copy()
        n = int((tn[0] - t0[0]) / h) #雑実装
        X = [[] for _ in range(num)]
        T = [[] for _ in range(num)]
        # 漸化式を計算
        for t_count in range(n):
            gradients = dxdt(x, t)
            for i in range(num):
                x[i] += gradients[i] * h
                X[i].append(x[i])
                t[i] = t0[i] + t_count * h
                T[i].append(t[i])
        return X, T
    
    num = 4
    X, T = euler(num, [0,1,2,5], [0 for _ in range(num)], [15 for _ in range(num)], 0.01)
    print(X)
    print(T)
    for i in range(len(T)):
        plt.plot(T[i], X[i])
    plt.show()