Skip to content

Instantly share code, notes, and snippets.

@PaulCreusy
Created July 17, 2024 12:38
Show Gist options
  • Save PaulCreusy/c69bcab7bb4faadc125ebb1ff42b8fea to your computer and use it in GitHub Desktop.
Save PaulCreusy/c69bcab7bb4faadc125ebb1ff42b8fea to your computer and use it in GitHub Desktop.
Interpolation functions
def create_interpolation_function(x_ref: list[float], y_ref: list[float]):
"""
Create an interpolation function with the given points.
Parameters
----------
x_ref : list[float]
X values.
y_ref : list[float]
Y values.
Returns
-------
Callable
Interpolation function.
"""
def interpolation_func(x: float):
if x < x_ref[0]:
return single_linear_interpolate(x_ref, y_ref, 0, 1, x)
for i in range(len(x_ref) - 1):
if x < x_ref[i + 1]:
return single_linear_interpolate(x_ref, y_ref, i, i + 1, x)
return single_linear_interpolate(x_ref, y_ref, len(x_ref) - 2, len(x_ref) - 1, x)
return interpolation_func
def get_slope(x_array: list[float], y_array: list[float], i: int, j: int):
"""
Get the slope of the curve between the two specified points.
Parameters
----------
x_array : list[float]
X values.
y_array : list[float]
Y values.
i : int
First point index.
j : int
Second point index.
Returns
-------
float
Slope of the curve.
"""
slope = (y_array[j] - y_array[i]) / (x_array[j] - x_array[i])
return slope
def single_linear_interpolate(x_array: list[float], y_array: list[float], i: int, j: int, x: float):
"""
Interpolate a single value on an affine curve.
Parameters
----------
x_array : list[float]
X values.
y_array : list[float]
Y values.
i : int
First point index.
j : int
Second point index.
x : float
Interpolation position.
Returns
-------
float
Interpolation value.
"""
slope = get_slope(x_array, y_array, i, j)
value = slope * (x - x_array[i]) + y_array[i]
return value
def interpolate(x_ref: list[float], y_ref: list[float], x_exp: list[float]):
"""
Interpolate the values defined on the ref points on the exp points.
Parameters
----------
x_ref : list[float]
y_ref : list[float]
x_exp : list[float]
Returns
-------
"""
interpolation_func = create_interpolation_function(x_ref, y_ref)
y_exp = []
for x in x_exp:
y_exp.append(interpolation_func(x))
return y_exp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment