[SciPy-User] cubic spline interpolation - derivative value in an end point

Eric Carlson ecarlson@eng.ua....
Mon Nov 26 17:45:13 CST 2012

On 11/26/2012 2:34 AM, Maxim wrote:
> Thank you, Eric.
> But there is a problem with the method you proposed (maybe you have overcome
> it...):
> I use 'smooth' parameter in splrep function, and there is a jump between first
> and second node which is smoothed out by splrep.
> If I add another node between the two, it will be just smoothed out again and
> thus it makes no impact on the derivative.
> Cheers,
> Maxim

If you are smoothing, then my original hack will definitely not work.

Given (xdata,ydata), instead of a direct fit maybe something like the 
following to brute force a zero slope:

import scipy as sp
import scipy.optimize as optimize
from numpy.random import randn
import scipy.interpolate as interpolate

ydata=sp.cos(xdata)+ randn(51)/10
smooth = 1.0
y_prime_target = 0.0
x_hack = -.2
x_for_yprime = 0
xfit=sp.insert(xdata,0,x_hack)# or something near x=0
def slope_hack(y_hack):
     yfit=sp.insert(ydata,0,y_hack)#just a placeholder
     f=interpolate.UnivariateSpline(xfit, yfit, k=3, s=smooth)
     return f(x_for_yprime,1)-y_prime_target
y_hack = 1.0
y_hack = optimize.fsolve(slope_hack, y_hack)
f_clamp=interpolate.UnivariateSpline(xfit, yfit, k=3, s=smooth)
f=interpolate.UnivariateSpline(xdata, ydata, k=3, s=smooth)
print 'derivative at x=0 for clamped',f_clamp(0,1), '\nderivative at x=0 
for regular', f(0,1)
import matplotlib.pyplot as plt

plt.plot(xdata,ydata, 'r.', label='data')
plt.plot(xplot, f_clamp(xplot),'-b', label='clamp fit')
plt.plot(xplot, f(xplot), '--g', label='normal fit')

More information about the SciPy-User mailing list