Skip to content

Instantly share code, notes, and snippets.

@bru32
Created August 13, 2025 04:31
Show Gist options
  • Save bru32/f1c0c798034b9ce5641b5bdea6ef1094 to your computer and use it in GitHub Desktop.
Save bru32/f1c0c798034b9ce5641b5bdea6ef1094 to your computer and use it in GitHub Desktop.
Closure to create an interpolator function
"""
Closure to create an interpolator function.
Bruce Wernick
13 August 2025
"""
def lagrange(xp, yp):
n = len(xp)
def inner(x):
value = 0.0
for j in range(n):
L = 1.0
for k in range(n):
if k != j:
L *= (x - xp[k]) / (xp[j] - xp[k])
value += yp[j] * L
return value
return inner
# given a sample data set X and Y.
X = [1,2,3,4,5]
Y = [2,4,6,8,10]
f = lagrange(X, Y) # get the interp function.
# Now, we can just call y = f(x)
# like any other function
x = 2.2
y = f(x)
print(f"x = {x}\ny = f({x}) = {y}")
# Plot the interpolated values with matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 5, 20)
#y = f(x) # <-- use the interp function f(x)
plt.plot(x, f(x)) # use y or f(x) directly.
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment