import numpy as np # numerics
import matplotlib.pyplot as plt # plotting
%matplotlib inline
#### Just plotting some data to visualize
x_given = np.array([0,1,2,3,4,5,6,7,8,9,10])
y_given = np.cos(x_given**2.0/8.0) + 1
plt.rc('font', size=16)
plt.plot(x_given, y_given, 'o:')
plt.plot([2.5,2.5],[-0.1,1.6], '--', color='gray')
plt.plot([-0.1,2.5],[1.6,1.6], '--', color='gray')
plt.plot([2.5], [1.6], '*', markersize=20)
plt.xlim([-0.1,11]); plt.ylim([-0.1,2.2])
plt.xlabel('x'); plt.ylabel('y')
plt.text(2.6,0, r"$x_w$", fontsize=16); plt.text(0,1.7, r"$y_w$", fontsize=16);
Linterp
that takes the following arguments:xg
an array of given x datayg
an array of given y data corresponding to xg
xw
the value of x we want to interpolate atyw
corresponding to xw
xg
are uniformly spaced, and ascending.Questions
#-------------------- Set some "given" x, y data, (normally given to us)
xg = np.array([0,1,2,3,4,5,6,7,8,9,10.]) # given x data
yg = np.cos(xg**2.0/8.0)+1 # given y data
print("xg = "+np.array2string(xg, formatter={'float_kind':lambda x: f"{x:4.2f}"}))
print("yg = "+np.array2string(yg, formatter={'float_kind':lambda x: f"{x:4.2f}"}))
#-------------------- interpolate to xw=2.5
xw = 2.5
xg = [0.00 1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00 10.00] yg = [2.00 1.99 1.88 1.43 0.58 0.00 0.79 1.99 0.85 0.24 2.00]
from scipy.interpolate import interp1d
interp1d
takes the given x array and the given y array as arguments.xg = np.array([0,1,2,3,4,5,6,7,8,9,10]) # given x data
yg = np.cos(xg**2.0/8.0)+1 # given y data
#---------------
f_interp = interp1d(xg, yg)
#---------------
xw = 2.5
yw = f_interp(xw)
print(yw)
1.6543795393445195
xx
xg = np.array([0,1,2,3,4,5,6,7,8,9,10]) # given x data
yg = np.cos(xg**2.0/8.0)+1 # given y data
Try this:
x
value that is outside of the bounds of the given xg
data.f_interp
with an x
value that is outside of the upper and lower bounds of the original xg
array.fill_value='extrapolate'
argument, like so:f_interp = interp1d(xg, yg, fill_value='extrapolate'
xg
, yg
fi=interp1d(xg, yg)
xw
intermediate points to interpolate at (can be an array).yw=fi(xw)
from scipy.interpolate import interp1d
xg = np.array([1,2,3,4,5]) # some data you have
yg = np.array([11, 2.2, 3.3, -88, 9])
fi = interp1d(xg,yg)
xw = 2.5
yw = fi(xw)
xg
and yg
arrays and you know the yw
and want to interpolate to the corresponding xw
?