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()