Feat: Ajoute l'exercice 1 de l'interpolation & extrapolation
This commit is contained in:
95
p1/ex5.py
Normal file
95
p1/ex5.py
Normal file
@@ -0,0 +1,95 @@
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
new_raph_steps = []
|
||||
dich_steps = []
|
||||
|
||||
|
||||
def f(x) -> float:
|
||||
return np.exp(x) - 2 * np.cos(x)
|
||||
|
||||
|
||||
def dichotomie(a, b, epsilon=1e-6, n=0) -> float:
|
||||
x = (a + b) / 2
|
||||
alpha = f(a) * f(x)
|
||||
dich_steps.append(x) # si on veut afficher les étapes
|
||||
|
||||
if np.abs(b - a) <= epsilon:
|
||||
return x
|
||||
|
||||
if alpha < 0:
|
||||
return dichotomie(a, x, epsilon, n+1)
|
||||
elif alpha == 0:
|
||||
return x
|
||||
else:
|
||||
return dichotomie(x, b, epsilon, n+1)
|
||||
|
||||
|
||||
def f_prime(x) -> float:
|
||||
return np.exp(x) + 2 * np.sin(x)
|
||||
|
||||
|
||||
def newton_raphson(x_0, epsilon, max_iter=1_000) -> float | None:
|
||||
"""
|
||||
Condition : connaître la dérivée de f(x)
|
||||
:param x_0:
|
||||
:param epsilon:
|
||||
:param max_iter:
|
||||
:return:
|
||||
"""
|
||||
x = x_0
|
||||
|
||||
for _ in range(max_iter):
|
||||
x_prev = x
|
||||
fx = f(x)
|
||||
fpx = f_prime(x)
|
||||
if np.abs(fx) < epsilon:
|
||||
return x
|
||||
elif fpx == 0:
|
||||
raise RuntimeError("Dérivée nulle : échec de Newton-Raphson.")
|
||||
x = x - (fx / fpx)
|
||||
new_raph_steps.append(x)
|
||||
if np.abs(x - x_prev) < epsilon:
|
||||
return x
|
||||
|
||||
raise RuntimeError(f"Newton-Raphson n'a pas convergé en {max_iter} itérations.")
|
||||
|
||||
|
||||
def ex1() -> None:
|
||||
x = np.arange(0, 1, 0.001)
|
||||
f = [np.exp(i) - 2 * np.cos(i) for i in x]
|
||||
f1 = [np.exp(i) for i in x]
|
||||
f2 = [2 * np.cos(i) for i in x]
|
||||
|
||||
for i in range(len(x)):
|
||||
if f1[i] == f2[i]:
|
||||
print(f1[i])
|
||||
|
||||
plt.plot(x, f)
|
||||
plt.plot(x, f1)
|
||||
plt.plot(x, f2)
|
||||
plt.grid()
|
||||
plt.show()
|
||||
|
||||
dichotomie_res = dichotomie(0, 1, 10e-6)
|
||||
print(dichotomie_res)
|
||||
|
||||
plt.plot(dich_steps)
|
||||
plt.title('Convergence de la dichotomie')
|
||||
plt.show()
|
||||
|
||||
newton_raphson_res = newton_raphson(0.1, 10e-6)
|
||||
print(newton_raphson_res)
|
||||
|
||||
plt.plot(new_raph_steps)
|
||||
plt.title('Convergence de Newton-Raphson')
|
||||
plt.show()
|
||||
|
||||
"""
|
||||
La NR à moins d'étape que la dichotomie, NR à l'air rapide,
|
||||
comme Flash McQueen (Kachow)
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ex1()
|
||||
Reference in New Issue
Block a user