简体   繁体   中英

Quadratic and Cubic Spline python

I used the interp1d, but I think the graph that the function is generating for the cubic is not right because it is the same as the quadratic. So if anyone can help me find the error in my code it would be of great help

Code in Python:

from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import numpy as np

x = [1.6, 2, 2.5, 3.2, 4, 4.5]
y = [2, 8, 14, 15, 8, 2]

f1 = interp1d(x, y, kind='quadratic')
f2 = interp1d(x, y, kind='cubic')

fig, axs = plt.subplots(4)
fig.suptitle(' Splines')


axs[0].plot(x, y, 'go')

# quadratic spline
axs[1].plot(x, y, 'go', x, f1(x),'m--')

# cubic spline
axs[2].plot(x, y, 'go', x, f2(x), 'b-.')


axs[3].plot(x, y, 'go', x, f1(x), 'r-', x, f2(x), 'b-.')
axs[3].legend(['data', 'quadratic', 'cubic'], loc='best')
plt.show()

image: 在此处输入图像描述

Splines are engineered to precisely hit the inputs that they were generated with. If you look at the data points you're plotting, you'll see that they're identical for both the quadratic and cubic cases because you're using the same x values that were used to produce the splines. The differences will become apparent when you start looking at points in between those inputs.

The curve you've chosen to test with is very gentle, so the difference between quadratic and cubic isn't visually apparent in a plot. But it's real n.netheless.

>>> [f1(n/10) for n in range(16,21)]
[array(2.), array(3.56757574), array(5.09010098), array(6.56757574), array(8.)]
>>> [f2(n/10) for n in range(16,21)]
[array(2.), array(3.47687906), array(4.98969223), array(6.50765929), array(8.)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM