Skip to content

Instantly share code, notes, and snippets.

@ekaitz-zarraga
Created July 7, 2023 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekaitz-zarraga/db21f35389df94a64e6284c80848dcf8 to your computer and use it in GitHub Desktop.
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
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