Feat: Ajoute la méthode des trapèzes et de Simpson
This commit is contained in:
9
tp6.py
9
tp6.py
@@ -147,6 +147,15 @@ def exercice3() -> None:
|
||||
a, b, c = moindre_carre(points)
|
||||
print(a,b,c)
|
||||
|
||||
results = []
|
||||
|
||||
for i in range(1, 7):
|
||||
results.append(f_h(a,b,c,t[i-1]))
|
||||
|
||||
plt.plot(results)
|
||||
plt.title('trajectoire du missile')
|
||||
plt.show()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
#exercice1()
|
||||
|
||||
69
tp7.py
Normal file
69
tp7.py
Normal file
@@ -0,0 +1,69 @@
|
||||
import numpy as np
|
||||
|
||||
|
||||
def trapeze_formule(f, a: float, b: float, n: int) -> float:
|
||||
"""
|
||||
|
||||
:param f: la fonction f (bien passer une fonction ou une lambda)
|
||||
:param a: la petite borne
|
||||
:param b: la grande borne
|
||||
:param n: nombre de "tranche" de calcul
|
||||
:return:
|
||||
"""
|
||||
|
||||
# dx = (b-a) / n
|
||||
dx = (b - a) / n
|
||||
|
||||
# somme_inferieure = sum de i = 1 jusqu'a n - 1 faire f(xi)
|
||||
somme_inferieure = 0.
|
||||
|
||||
for i in range(1, n):
|
||||
xi = a + i * dx
|
||||
somme_inferieure += f(xi)
|
||||
|
||||
# I = (delta X / 2) * [f(a) + f(b) + 2 * somme_inferieure ]
|
||||
I = (dx / 2) * (f(a) + f(b) + 2 * somme_inferieure)
|
||||
return I
|
||||
|
||||
|
||||
def simpson(f, a: float, b: float, n: int) -> float:
|
||||
if n % 2 != 0:
|
||||
raise ValueError(f'n must be even, got {n}')
|
||||
|
||||
dx = (b - a) / n
|
||||
|
||||
somme_paire = 0.
|
||||
somme_impaire = 0.
|
||||
|
||||
for i in range(1, n):
|
||||
xi = a + i * dx
|
||||
if i % 2 == 0:
|
||||
somme_paire += f(xi)
|
||||
else:
|
||||
somme_impaire += f(xi)
|
||||
|
||||
I = (dx / 3) * (f(a) + f(b) + 4 * somme_impaire + 2 * somme_paire)
|
||||
return I
|
||||
|
||||
|
||||
def exercice1():
|
||||
f = lambda x: x ** 2
|
||||
approx = trapeze_formule(f, a=0, b=1, n=10)
|
||||
print(approx)
|
||||
|
||||
g = lambda x : np.sin(x)
|
||||
trapeze1 = trapeze_formule(g, a=0, b=np.pi, n=100)
|
||||
trapeze2 = trapeze_formule(g, a=0, b=np.pi, n=200)
|
||||
|
||||
simpson1 = simpson(g, a=0, b=np.pi, n=100)
|
||||
simpson2 = simpson(g, a=0, b=np.pi, n=200)
|
||||
|
||||
# le vrai résultat est 2.
|
||||
print(f'{trapeze1}, {trapeze2} erreur: {2-trapeze1} {2-trapeze2}')
|
||||
print(f'{simpson1}, {simpson2} erreur: {2 - simpson1} {2 - simpson2}')
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
exercice1()
|
||||
Reference in New Issue
Block a user