I'll post some more detailed example codeHowever, all of that can be replaced with a call to interp1d
:
import numpy as np
from scipy.interpolate import interp1d
def interpolate_arrays(bounds, n_steps=10):
"""final function that interpolates arrays"""
bounds = np.array(bounds)
fun = interp1d(
x=[0, 1],
y=bounds.T,
)
y = fun(np.linspace(0, 1, n_steps))
return y
def test():
X1 = [1.5, 1]
X2 = [5.5, 3]
y = interpolate_arrays([X1, X2], n_steps=3)
assert y.T.tolist() == [[1.5, 1.0], [3.5, 2.0], [5.5, 3.0]]
Even easier:
def interpolate_arrays(X1, X2, n_steps=10):
"""final function that interpolates arrays"""
return np.linspace(X1, X2, n_steps)
def test():
X1 = [1.5, 1]
X2 = [5.5, 3]
y = interpolate_arrays(X1, X2, n_steps=3)
assert y.tolist() == [[1.5, 1.0], [3.5, 2.0], [5.5, 3.0]]
Notes:
- If you use
interp1d
, it would be better if your inputs and outputs are both two-dimensionalnp.ndarray
; in their current form they need a transposition - Write some unit tests such as the one shown, although it would be a better idea to call
isclose
since this is floating-point math - If you want, it is trivial to make this extrapolate as well as interpolate
Basically: if there is a math thing in your head, before even thinking about what it would take to implement it yourself, do a bitsearch through scipy
/numpy
to see if it has already been done for you.