Spline Example

In [1]:
import numpy as np
from scipy.interpolate import make_interp_spline
import matplotlib.pyplot as plt
%matplotlib inline

Revisit Monomial Interpolation Case

In [2]:
x = np.arange(10, dtype=float)
y = np.zeros_like(x)
y[5:] = 1.
plt.plot(x,y,'ro')
plt.axis('equal');

Spline Interpolant

In [3]:
# Simple (default) spline
cs = make_interp_spline(x,y)
In [4]:
# It returns a function
cs
Out[4]:
<scipy.interpolate._bsplines.BSpline at 0x10d044f98>
In [5]:
cs(3.5)
Out[5]:
array(-0.10060976)
In [6]:
cs([5.3, 2.11])
Out[6]:
array([1.10397561, 0.0060889 ])

Plot it

In [7]:
xx = np.linspace(x[0],x[-1],100)
yy = [cs(x) for x in xx]
In [8]:
plt.plot(xx,yy)
plt.plot(x,y, 'ro')
plt.axis('equal');

Boundary conditions

In [9]:
# Spline with specified boundary conditions
left = [(1,1)]  # First deriv = 1
right = [(1,-10.2)] # First deriv = -10.2
cs = make_interp_spline(x,y, bc_type=(left, right))
In [10]:
xx = np.linspace(x[0],x[-1],100)
yy = [cs(x) for x in xx]
plt.plot(xx,yy)
plt.plot(x,y, 'ro')
plt.axis('equal');

Another Example

In [11]:
y = [4, 8, 7, 5, 1, 2, 9, 7, 8, 9, 0]
N = len(y)
x = np.arange(300, N+300)

plt.plot(x, y, 'ro');
In [12]:
cs = make_interp_spline(x, y)
In [13]:
xx = np.linspace(x[0], x[-1], 100)
plt.plot(x, y, 'ro')
plt.plot(xx, cs(xx));
#plt.savefig('spline_example.png')
In [ ]: