Vous êtes sur la page 1sur 8

22/01/2024 21:29 TP1HYSNUM.

ipynb - Colaboratory

# Importation de la libretie
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

QUESTION 1

Fonction Python qui utilise la méthode d’Euler pour résoudre une équation différentielle de la forme y′=f(t,y) avec y(a)=y0.

def euler(f, a, b, y0, N):


h = (b - a) / float(N - 1)
t = a
y = y0
result = [(t, y)]
for n in range(N - 1):
y = y + h * f(t, y)
t = a + (b - a) * (n + 1) / (N - 1)
result.append((t, y))
return result

Double-cliquez (ou appuyez sur Entrée) pour modifier

def f(t, y):


return t - y

# Paramètres de la méthode d'Euler


a = 0
b = 2
y0 = 1
N = 100

# Résolution de l'équation différentielle


solution = euler(f, a, b, y0, N)

# Affichage de la solution
for t, y in solution:
print(f"t = {t}, y = {y}")

https://colab.research.google.com/drive/1VlkHzhW19b2Vmacx5wZ4RIc-SbrPLJhL#printMode=true 1/8
22/01/2024 21:29 TP1HYSNUM.ipynb - Colaboratory
t = 1.6767676767676767, y = 1.0443569149464353
t = 1.696969696969697, y = 1.057132889932723
t = 1.7171717171717171, y = 1.0700588860344802
t = 1.7373737373737375, y = 1.083131872522101
t = 1.7575757575757576, y = 1.0963488798928411
t = 1.7777777777777777, y = 1.10970699863391
t = 1.797979797979798, y = 1.123203378010554
t = 1.8181818181818181, y = 1.1368352248786195
t = 1.8383838383838385, y = 1.1505998025211084
t = 1.8585858585858586, y = 1.1644944295082342
t = 1.878787878787879, y = 1.1785164785805096
t = 1.898989898989899, y = 1.1926633755543958
t = 1.9191919191919191, y = 1.2069325982500625
t = 1.9393939393939394, y = 1.2213216754408072
t = 1.9595959595959596, y = 1.2358281858236988
t = 1.97979797979798, y = 1.2504497570110171
t = 2.0, y = 1.2651840645420669

Programme Python qui utilise la fonction euler pour résoudre l’équation différentielle y′+y=t sur l’intervalle [0,2] avec la condition initiale y(0)=1.

# Définition de la solution analytique de l'équation différentielle


def analytical_solution(t):
return t - 1 + 2 * np.exp(-t)

# Définition de la méthode d'Euler


def euler(f, a, b, y0, N):
h = (b - a) / float(N - 1)
t = a
y = y0
result = [(t, y)]
for n in range(N - 1):
y = y + h * f(t, y)
t = a + (b - a) * (n + 1) / (N - 1)
result.append((t, y))
return np.array(result)[:,0], np.array(result)[:,1]

# Paramètres de la méthode d'Euler


a, b = 0, 2
y0 = 1
N = 100

# Résolution de l'équation différentielle avec la méthode d'Euler


t, y_euler = euler(f, a, b, y0, N)

# Calcul de la solution analytique


y_analytical = analytical_solution(t)

# Tracé des solutions numérique et analytique


plt.plot(t, y_euler, label='Euler')
plt.plot(t, y_analytical, label='Solution analytique', linestyle='dashed')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.legend()
plt.show()

https://colab.research.google.com/drive/1VlkHzhW19b2Vmacx5wZ4RIc-SbrPLJhL#printMode=true 2/8
22/01/2024 21:29 TP1HYSNUM.ipynb - Colaboratory
# Calcul de l'erreur relative
error = np.abs((y_euler - y_analytical) / y_analytical)
max_error = np.max(error)
print(f'Erreur maximale : {max_error:.2%}')

Erreur maximale : 1.05%

QUESTION 2

Fonctions de Runge-Kutta d’ordre 2 et 4 respectivement :

def rk2(f, a, b, y0, N):


h = (b - a) / float(N - 1)
t = np.linspace(a, b, N)
y = np.zeros(N)
y[0] = y0
for i in range(1, N):
k1 = h * f(y[i - 1], t[i - 1])
k2 = h * f(y[i - 1] + k1 / 2, t[i - 1] + h / 2)
y[i] = y[i - 1] + k2
return t, y

def rk4(f, a, b, y0, N):


h = (b - a) / float(N - 1)
t = np.linspace(a, b, N)
y = np.zeros(N)
y[0] = y0
for i in range(1, N):
k1 = h * f(y[i - 1], t[i - 1])
k2 = h * f(y[i - 1] + k1 / 2, t[i - 1] + h / 2)
k3 = h * f(y[i - 1] + k2 / 2, t[i - 1] + h / 2)
k4 = h * f(y[i - 1] + k3, t[i - 1] + h)
y[i] = y[i - 1] + (k1 + 2 * k2 + 2 * k3 + k4) / 6
return t, y

Ce script utilise les fonctions rk2 et rk4 que nous avons écrites précédemment, ainsi que la fonction odeint de la bibliothèque scipy.integrate,
pour résoudre l’équation différentielle y′+y=t avec la condition initiale y(0)=1.

def f(y, t):


return t - y

def rk2(f, a, b, y0, N):


h = (b - a) / (N - 1)
t = np.linspace(a, b, N)
y = np.zeros(N)
y[0] = y0
for i in range(1, N):
k1 = h * f(y[i - 1], t[i - 1])
k2 = h * f(y[i - 1] + k1 / 2, t[i - 1] + h / 2)
y[i] = y[i - 1] + k2
return t, y

def rk4(f, a, b, y0, N):


h = (b - a) / (N - 1)
t = np.linspace(a, b, N)
y = np.zeros(N)
y[0] = y0
for i in range(1, N):
k1 = h * f(y[i - 1], t[i - 1])
k2 = h * f(y[i - 1] + k1 / 2, t[i - 1] + h / 2)
k3 = h * f(y[i - 1] + k2 / 2, t[i - 1] + h / 2)
k4 = h * f(y[i - 1] + k3, t[i - 1] + h)
y[i] = y[i - 1] + (k1 + 2 * k2 + 2 * k3 + k4) / 6
return t, y

def analytical_solution(t):
return t - 1 + 2 * np.exp(-t)

a, b = 0, 2
y0 = 1
N = 10
t, y_rk2 = rk2(f, a, b, y0, N)
t, y_rk4 = rk4(f, a, b, y0, N)
y_odeint = odeint(f, y0, t).flatten()
y_analytical = analytical_solution(t)

plt.plot(t, y_rk2, label='Runge-Kutta 2')


plt.plot(t, y_rk4, label='Runge-Kutta 4')
lt l t(t d i t l b l ' d i t' li t l 'd h d')
https://colab.research.google.com/drive/1VlkHzhW19b2Vmacx5wZ4RIc-SbrPLJhL#printMode=true 3/8
22/01/2024 21:29 TP1HYSNUM.ipynb - Colaboratory
plt.plot(t, y_odeint, label='odeint', linestyle='dashed')
plt.plot(t, y_analytical, label='Analytical Solution', linestyle='dotted')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.legend()
plt.show()

# Calcul de l'erreur relative


error_rk2 = np.abs((y_rk2 - y_analytical) / y_analytical)
error_rk4 = np.abs((y_rk4 - y_analytical) / y_analytical)
error_odeint = np.abs((y_odeint - y_analytical) / y_analytical)
print(f'Max error RK2: {np.max(error_rk2):.1%}')
print(f'Max error RK4: {np.max(error_rk4):.1%}')
print(f'Max relative error odeint: {np.max(error_odeint):.1%}')

output

Max error RK2: 1.0%


Max error RK4: 0.0%
Max relative error odeint: 0.0%

Zoom 1

a, b = 1, 2
y0 = 1
N = 100
t, y_rk2 = rk2(f, a, b, y0, N)
t, y_rk4 = rk4(f, a, b, y0, N)
y_odeint = odeint(f, y0, t).flatten()
y_analytical = analytical_solution(t)

plt.plot(t, y_rk2, label='Runge-Kutta 2')


plt.plot(t, y_rk4, label='Runge-Kutta 4')
plt.plot(t, y_odeint, label='odeint', linestyle='dashed')
plt.plot(t, y_analytical, label='Analytical Solution', linestyle='dotted')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.legend()
plt.show()

https://colab.research.google.com/drive/1VlkHzhW19b2Vmacx5wZ4RIc-SbrPLJhL#printMode=true 4/8
22/01/2024 21:29 TP1HYSNUM.ipynb - Colaboratory

Zoom 2

a, b = 0.6,0.9
y0 = 1
N = 10
t, y_rk2 = rk2(f, a, b, y0, N)
t, y_rk4 = rk4(f, a, b, y0, N)
y_odeint = odeint(f, y0, t).flatten()
y_analytical = analytical_solution(t)

plt.plot(t, y_rk4, label='Runge-Kutta 4')


plt.plot(t, y_odeint, label='odeint', linestyle='dashed')
plt.plot(t, y_analytical, label='Analytical Solution', linestyle='dotted')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.legend()
plt.show()

Zoom 3

https://colab.research.google.com/drive/1VlkHzhW19b2Vmacx5wZ4RIc-SbrPLJhL#printMode=true 5/8
22/01/2024 21:29 TP1HYSNUM.ipynb - Colaboratory
a, b = 0.6,0.9
y0 = 1
N = 10
t, y_rk2 = rk2(f, a, b, y0, N)
t, y_rk4 = rk4(f, a, b, y0, N)
y_odeint = odeint(f, y0, t).flatten()
y_analytical = analytical_solution(t)

plt.plot(t, y_rk2, label='Runge-Kutta 2')


#plt.plot(t, y_rk4, label='Runge-Kutta 4')
plt.plot(t, y_odeint, label='odeint', linestyle='dashed')
plt.plot(t, y_analytical, label='Analytical Solution', linestyle='dotted')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.legend()
plt.show()

QUESTION 3

https://colab.research.google.com/drive/1VlkHzhW19b2Vmacx5wZ4RIc-SbrPLJhL#printMode=true 6/8
22/01/2024 21:29 TP1HYSNUM.ipynb - Colaboratory
# Définition des fonctions
def f1(y1, y2):
return y2

def f2(y1, y2):


return -g / l * np.sin(y1)

def runge_kutta_4(f1, f2, y1_0, y2_0, t):


h = t[1] - t[0]
y1 = [y1_0]
y2 = [y2_0]
for i in range(len(t) - 1):
k11 = h * f1(y1[-1], y2[-1])
k12 = h * f2(y1[-1], y2[-1])
k21 = h * f1(y1[-1] + k11 / 2, y2[-1] + k12 / 2)
k22 = h * f2(y1[-1] + k11 / 2, y2[-1] + k12 / 2)
k31 = h * f1(y1[-1] + k21 / 2, y2[-1] + k22 / 2)
k32 = h * f2(y1[-1] + k21 / 2, y2[-1] + k22 / 2)
k41 = h * f1(y1[-1] + k31, y2[-1] + k32)
k42 = h * f2(y1[-1] + k31, y2[-1] + k32)
y1.append(y1[-1] + (k11 + 2 * k21 + 2 * k31 + k41) / 6)
y2.append(y2[-1] + (k12 + 2 * k22 + 2 * k32 + k42) / 6)
return y1, y2

# Paramètres
g = 9.81 # accélération due à la gravité en m/s^2
l = 9.81 / 100 # longueur du pendule en m
y1_0 = np.radians(10) # angle initial en radians
y2_0 = 0 # vitesse angulaire initiale en rad/s
t = np.linspace(0, 10, 1000) # intervalle de temps

# Solution numérique
y1, y2 = runge_kutta_4(f1, f2, y1_0, y2_0, t)

# Solution analytique pour les petites oscillations


theta_analytical = y1_0 * np.cos(np.sqrt(g / l) * t)

# Tracer les solutions


plt.figure(figsize=(10, 6))
plt.plot(t, y1, label='Solution RK4')
plt.plot(t, theta_analytical, label='Solution analytique', linestyle='--')
plt.xlabel('Temps (s)')
plt.ylabel('Theta(t) (radians)')
plt.legend()
plt.show()

Quzstion 4

https://colab.research.google.com/drive/1VlkHzhW19b2Vmacx5wZ4RIc-SbrPLJhL#printMode=true 7/8
22/01/2024 21:29 TP1HYSNUM.ipynb - Colaboratory
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad

# Paramètres
g = 9.81 # accélération due à la gravité en m/s^2
l = 9.81 / 100 # longueur du pendule en m
theta0_values = np.linspace(0.01, np.pi, 100) # valeurs de theta0

# Calcul de la période des oscillations pour chaque valeur de theta0


T_values = []
f th d'établir
Impossible t 0 i uneth connexion
t 0 l avec le service reCAPTCHA. Veuillez vérifier votre connexion Internet, puis actualiser la page pour afficher une image reCAPTCHA.

https://colab.research.google.com/drive/1VlkHzhW19b2Vmacx5wZ4RIc-SbrPLJhL#printMode=true 8/8

Vous aimerez peut-être aussi