Last active
September 18, 2021 15:46
-
-
Save fionn/374b1a7e1f0b624170135172b995d3c9 to your computer and use it in GitHub Desktop.
Lagrange polynomial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LagrangePolynomial: | |
def __init__(self, x_points: list[float], y_points: list[float]) -> None: | |
self.xs = x_points | |
self.ys = y_points | |
def _basis(self, x: float, j: int) -> float: | |
"""Lagrange basis polynomial l_j(x)""" | |
x_j = self.xs[j] | |
product = 1.0 | |
for x_m in self.xs: | |
if x_m != x_j: | |
product *= (x - x_m) / (x_j - x_m) | |
return product | |
def lagrange_poly(self, x: float) -> float: | |
"""Lagrange polynomial at x""" | |
total = 0.0 | |
for j in range(len(self.ys)): | |
total += self.ys[j] * self._basis(x, j) | |
return total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment