- Euler’s Method by Python
- https://algorithm.joho.info/mathematics/euler-method-program/
- The code here is the original source.
- For Kineto’s elastic synchronization algorithm, use eular.py
import matplotlib.pyplot as plt
import math
import numpy as np
# Function for the differential equation
def dxdt(x, t):
gradients = []
for i in range(len(x)):
gradients.append(1)
return gradients
# Euler's method
def euler(num, x0, t0, tn, h):
x = x0.copy()
t = t0.copy()
n = int((tn[0] - t0[0]) / h) # Rough implementation
X = [[] for _ in range(num)]
T = [[] for _ in range(num)]
# Calculate the recurrence relation
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()
The code above is an implementation of Euler’s Method in Python. It calculates the approximate solution to a system of differential equations.
The dxdt
function represents the derivatives of the variables in the system. In this example, it returns a list of 1s, indicating that all variables have a constant rate of change.
The euler
function performs the Euler’s Method calculation. It takes the number of variables (num
), initial values for the variables (x0
), initial time (t0
), final time (tn
), and step size (h
) as inputs. It returns lists X
and T
, which contain the values of the variables and corresponding time points at each iteration.
In the example code, Euler’s Method is used to approximate the solution for a system of 4 variables. The initial values for the variables are [0, 1, 2, 5], and the time range is from 0 to 15. The step size is set to 0.01. The calculated values are printed and plotted using matplotlib.