Created
July 7, 2023 08:48
-
-
Save ekaitz-zarraga/db21f35389df94a64e6284c80848dcf8 to your computer and use it in GitHub Desktop.
Lagrange Interpolation using a closure and a namedtuple vs a class and a dataclass
This file contains hidden or 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
from collections import namedtuple | |
Point = namedtuple('Point', ['x', 'y']) | |
def lagrange_interp(points): | |
def interp(x): | |
y = 0 | |
for pj in points: | |
l = 1 | |
xj = pj.x | |
for pi in points: | |
xi = pi.x | |
if xi == xj: | |
continue | |
l *= (x - xi) / (xj - xi) | |
y += pj.y * l | |
return y | |
return interp | |
f = lagrange_interp( [Point(0,0), Point(1,1)] ) | |
f(19) # => 19 | |
## Class style: | |
from dataclasses import dataclass | |
@dataclass | |
class Point: | |
x: float | |
y: float | |
class lagrange_interp: | |
def __init__(self, points): | |
self.points = points | |
def __call__(self, x): | |
y = 0 | |
for pj in self.points: | |
l = 1 | |
xj = pj.x | |
for pi in self.points: | |
xi = pi.x | |
if xi == xj: | |
continue | |
l *= (x - xi) / (xj - xi) | |
y += pj.y * l | |
return y | |
f = lagrange_interp( [Point(0,0), Point(1,1)] ) | |
f(19) # => 19 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment