python-scipyHow do I use Python and SciPy to perform spline interpolation?
Spline interpolation is a method of constructing new data points within the range of a discrete set of known data points. Python and SciPy provide a convenient set of functions for performing spline interpolation.
Example code
import numpy as np
from scipy.interpolate import interp1d
# Create a set of data points
x = np.linspace(0, 10, num=11, endpoint=True)
y = np.cos(-x**2/9.0)
# Create a linear interpolation function
f = interp1d(x, y)
# Interpolate at new points
xnew = np.linspace(0, 10, num=41, endpoint=True)
ynew = f(xnew)
The code above creates a set of data points x
and y
and then creates a linear interpolation function f
using interp1d
. The function f
is then used to interpolate at new points xnew
and ynew
.
Code explanation
import numpy as np
: imports the NumPy library asnp
from scipy.interpolate import interp1d
: imports theinterp1d
function from the SciPy libraryx = np.linspace(0, 10, num=11, endpoint=True)
: creates a set of data pointsx
between 0 and 10 with 11 pointsy = np.cos(-x**2/9.0)
: creates a set of data pointsy
for eachx
point using the cosine functionf = interp1d(x, y)
: creates a linear interpolation functionf
usinginterp1d
xnew = np.linspace(0, 10, num=41, endpoint=True)
: creates a set of new pointsxnew
between 0 and 10 with 41 pointsynew = f(xnew)
: uses the linear interpolation functionf
to interpolate at the new pointsxnew
and creates a set of new pointsynew
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to find the zeros of a function?
- How do I create a numpy array of zeros using Python?
- How do I use the trapz function in Python SciPy?
- How do I convert a Python numpy.ndarray to a list?
- How do I use Python Scipy to perform a Z test?
- How can I use Python and Numpy to parse XML data?
- How do I create a numpy array of zeros using Python?
- How do I use the scipy ttest_ind function in Python?
- How do I calculate a Jacobian matrix using Python and NumPy?
See more codes...