Files
2020-05-29 15:25:49 -06:00

43 KiB

In [4]:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline

Example of cubic spline, a function which constructs polynomials of degree >= 3 between each (x,y) cordinate on a plot.The cubic spline creates polynomials that are twice differentiable, meaning that at each x coordinate, the two polynomials that hit that point will have the same y value at that particular x value when you take the second derivate of each polynomial. This is used to create a line that is smooth and has no sharp edges.

In [5]:
#create an array of x values from 0 to 4 inclusive and an empty array of y values
x = np.array([0,1,2,3,4]); y = np.array([])
#prompt the user to enter y coordinates for each x coordinate
print('Enter 5 y coordinate values')
#save each y value in the y array
for i in range (0, 5):
    yval = int(input('y'))
    y = np.append(y, yval)
#use the CubicSpline function to create the spline
spline = CubicSpline(x, y, bc_type = 'natural')
#plot all of the (x,y) coordinates
plt.scatter(x, y, label = 'Coordinates')
#plot the linear polynomials going through each point
plt.plot(x, y, label = 'Linear Polynomial Interpolant', color = 'Black')
#plot the cubic spline line
t = np.arange(x[0], x[-1]+ 0.01, 0.01)
plt.plot(t, spline(t), label = 'Cubic Spline', color = 'Red')
plt.legend()
Out [5]:
Enter 5 y coordinate values
y 12
y 2
y 5
y 3
y 14
<matplotlib.legend.Legend at 0x11ecbe710>
In [6]:
#plot the cubic spline, showing each piece of the spline in a different color
section1 = np.arange(x[0], x[1] + 0.01, 0.01)
section2 = np.arange(x[1], x[2] + 0.01, 0.01)
section3 = np.arange(x[2], x[3] + 0.01, 0.01)
section4 = np.arange(x[3], x[4] + 0.01, 0.01)
plt.scatter(x, y)
plt.plot(section1, np.polyval(spline.c[:,0], section1-x[0]))
plt.plot(section2, np.polyval(spline.c[:,1], section2-x[1]))
plt.plot(section3, np.polyval(spline.c[:,2], section3-x[2]))
plt.plot(section4, np.polyval(spline.c[:,3], section4-x[3]))
Out [6]:
[<matplotlib.lines.Line2D at 0xb20dee8d0>]
In [ ]: