-
Discrete differentiation (time step is the minimum unit).
-
https://algorithm.joho.info/mathematics/euler-method-program/
- I read this and understood it.
- Note: In the above page, the variable “t” corresponds to “x” in the definition of the derivative function, and “x” corresponds to “y”.
- Note: In this example, the function dxdt() takes only “x” as an argument, but it should actually take both “x” and “t”.
- https://qiita.com/Sunset_Yuhi/items/fb574091fe380e677735
- This one is more accurate and better code.
euler.py
import matplotlib.pyplot as plt
import math
# Function for the differential equation
# When x is this value,
def dxdt(x, t):
return math.sin(t)
# Euler's method
def euler(x0, t0, tn, h):
x = x0
t = t0
n = int((tn - t0) / h)
X = []
T = []
# Calculate the recurrence formula
for i in range(n):
x += dxdt(x, t) * h
X.append(x)
t = t0 + i * h
T.append(t)
return X, T
# Test sin wave with various values of lim h->0
# The finer the approximation, the better
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()