import numpy as np
import matplotlib.pyplot as plt
Euler’s Method
Euler’s method is a simple numerical technique used to approximate the solutions of ordinary differential equations (ODEs). It works by iteratively calculating the values of a function at discrete time steps.
Import Libraries
Exact Equation
Define the Equation
\[\large v = \frac{m \cdot g}{c} \cdot \left( 1 - e^{\large -\frac{ \large c \cdot t}{\large m}}\right) \]
def eqn(t, m, g, c):
= (m*g/c)*(1-np.exp(-c*t/m))
v return v
Generate x values
= np.linspace(0, 40, 400) x
Constants
=80 #(Mass = 80 Kg)
m=9.81 #(Gravitational Const. = 9.81 m/s^2)
g=12.5 #(Drag Coeff. = 12.5 Kg/s)
c=0 #(Given that at t=0, v=0) v_0
Calculate y values
= eqn(x, m, g, c) y
Plotting the Exact Function
plt.plot(x, y)'t')
plt.xlabel('v')
plt.ylabel('Plot of Exact Equation')
plt.title(True)
plt.grid( plt.show()
Euler’s Method
\[ \large f(t + h) = f(t) + h \cdot f'(t) \]
Define Differential Eqn
def differential_eqn(v,t):
return g-c*v/m
Generate x values with step size
=1
step= np.linspace(0, 40, int(40/step)) x_e
Calculate y values
=np.zeros(len(x_e))
y_e0]=v_0
y_e[
for i in range(len(x_e)-1):
+1]=y_e[i]+differential_eqn(y_e[i],x_e)*step y_e[i
Plotting the Estimated Function
plt.plot(x_e, y_e)'t')
plt.xlabel('v')
plt.ylabel('Plot of Estimated Equation')
plt.title(True)
plt.grid( plt.show()
Calculating the error
="Solving by Euler's Eqn")
plt.plot(x_e, y_e, label="Solving by Exact Eqn")
plt.plot(x, y, label'Plot of Exact and Estimated Equation')
plt.title(
plt.legend() plt.show()
=y[::10]+1e-15
y1
= np.abs(y1 - y_e)
absolute_error = (absolute_error / y1) * 100
percentage_error = np.mean(percentage_error)
average_percentage_error
print("Average Percentage Error:", average_percentage_error, "%")
Average Percentage Error: 4.475024083304925 %