from dataclasses import dataclass import matplotlib.pyplot as plt import numpy as np @dataclass class Point: x: float y: float def interpolation_lagrange(points: list[Point], x: float, show_polynome: bool=False) -> float: """ :param points: Les points de la courbe représentant une fonction :param x: le x en entrée de la fonction où on veut interpoler :return: L'interpolation """ interpolation: float = 0. n = len(points) # nombre de points for i in range(n): term: float = 1. # 0.0 will always give 0, it's a product ! So lets put 1 # Lagrange L(x) for k in range(n): if k != i: term *= ((x - points[k].x) / (points[i].x - points[k].x)) # erreur ici, voir le chat if show_polynome: print(f'P(x) = (({x} - {points[k].x}) / ({points[i].x} - {points[k].x}))') # interpolation with a piece of Lagrange (y_i) interpolation += term * points[i].y return interpolation def interpolation_newton(points: list[Point], x: float) -> float: interpolation = 0. # alpha sum n = len(points) for i in range(n): a_i = 1. for k in range(n-1): a_i *= (points[k+1].y - points[k].y) / (points[k+1].x - points[k].x) return interpolation def interpolation_moindre_carree(points: list[Point], x: float) -> float: interpolation = 0. pass def test() -> None: points = [Point(0, 1), Point(1, 3), Point(2, 2)] x = 1.5 result = interpolation_lagrange(points, x) print(f"P({x}) = {result}") # Doit afficher 2.875 def exercice1() -> None: points = [Point(-1,0), Point(0,-1), Point(1,0), Point(3,70)] inter_x2 = interpolation_lagrange(points, 2, True) inter_x3 = interpolation_lagrange(points, 3, True) print(f"X2={inter_x2}, X3={inter_x3}") x = np.linspace(0, 4, 300) y = [interpolation_lagrange(points, x[i]) for i in range(len(x))] # extrapolation plt.plot(x, y) plt.title('fonction f(x) ex 1') plt.show() def exercice2() -> None: pass if __name__ == '__main__': exercice1()