I am using the InterpolatedUnivariateSpline
function from the scipy.interpolate
library. I know that there exists a function the evaluate the derivative of the resulting spline. What I am interested in is the derivative of the log of the spline. Is there a way to calculate this directly?

- 304
- 2
- 12
-
Would writing it yourself using the chain rule be an option? – FlyingTeller Mar 21 '18 at 12:25
-
Yes. I don't know, why I did not think in this way. Anyhow, the question remains, if you can define a function, depending on a spline, which can be differentiated by python (analytically)? I think this is the case for splines, since the polynomial functions are easily differentiated analytically. – Daniel Mar 21 '18 at 12:30
-
One could take the spline of the log of your data. Then the derivative is available directly. – Jon Custer Mar 21 '18 at 19:05
-
Yes, but this is not the same, since on has to use the chain rule, as stated above. – Daniel Mar 22 '18 at 08:48
1 Answers
FlyingTeller's suggestion is probably optimal: the derivative of log(f) is f'/f
which is easy enough to implement:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import InterpolatedUnivariateSpline
x = np.arange(1, 9)
y = np.sqrt(x) # something to use as y-values
spl = InterpolatedUnivariateSpline(x, y)
logder = lambda x: spl.derivative()(x)/spl(x) # derivative of log of spline
t = np.linspace(x.min(), x.max())
plt.plot(t, logder(t))
plt.show()
Constructing a spline based on the logarithm of data is also a reasonable approach, but it is not the same thing as the logarithm of the original spline.
if you can define a function, depending on a spline, which can be differentiated by python (analytically)
Differentiating an arbitrary function analytically is out of scope for SciPy. In the above example, I had to know that the derivative of log(x)
is 1/x
; SciPy does not know that. SymPy is a library for symbolic math operations such as derivatives.
It's possible to use SymPy to find the derivative of a function symbolically and then turn it, using lambdify
, into a callable function that SciPy or matplotlib, etc can use.
One can also work with splines in an entirely symbolic way using SymPy but it's slow.