我有一组数据点,希望用样条函数来近似它们。我使用了两种不同的函数:
- scipy中的splrep函数
- 我在这里找到的一个三次样条函数。
from matplotlib.pyplot import *
from numpy import *
from scipy import interpolate
#----------------------------------------------
s = arange(257)/256.0
z = s[::-1]
b = transpose(array((z*z*z,
3*z*z*s,
3*z*s*s,
s*s*s)))
def cubicspline(c,t):
return dot(b[t],c)
#----------------------------------------------
A = array([
[ -126.041 , 246.867004],
[ -113.745003, 92.083 ],
[ 208.518997, -183.796997],
[ 278.859009, -190.552994]])
a1 = A[:,0]
a2 = A[:,1]
cs = reshape(A, (-1, 4, 2))
X = []
Y = []
#spline with cubicspline()
for (x,y) in [cubicspline(c,16*t) for c in cs for t in arange(17)]:
X.append(x)
Y.append(y)
# spline with splrep
tck = interpolate.splrep( a1, a2)
xnew = np.arange( min(a1), max(a1), 5)
ynew = interpolate.splev(xnew, tck)
plot(a1, a2, "--ob", ms = 9, label = "points")
plot(X, Y, "r", lw=2, label = "cubicspline")
plot(xnew, ynew, "g", lw=2, label = "splrep")
legend(); savefig("image.png"); show()
你可能已经看到了splrep的结果远非令人满意。 有人能解释一下这种行为,以及如何从splrep中获得合理的近似值吗?