How to get derivatives from 1D interpolation

Is there a way to get scipy interp1d (in linear mode) to return the derivative at each interpolated point? I could of course write my own 1D interpolation routine which is, but presumably scipy internally in C and therefore faster, and speed is already a major issue.

I end up suppressing the entanglement of the interpolated function into a multidimensional minimization routine, so being able to pass analytic derivatives will speed things up a lot, rather than running the minimization routine to compute them yourself. And interp1d has to calculate them internally --- so I can access them?

+3


source to share


2 answers


Use UnivariateSpline

instead interp1d

and use the method derivative

to create the first derivative. The example on the man page here is pretty self explanatory.



+4


source


You can combine scipy.interpolate.interp1d and scipy.misc.derivative , but something needs to be considered:

When calling the method derivative

with some dx

one selected as an interval, the derivative of x0

will be calculated as the difference of the first order between x0-dx

and x0+dx

:

derivative(f, x0, dx) = (f(x0+dx) - f(x0-dx)) / (2 * dx)

      

As a result, you cannot use derivative

closer than dx

your interpolated function range ranges, because it f

will raise a ValueError, telling you that your interpolated function is not defined there.

So what can you do closer than dx

these range limits?

If f

defined inside [xmin, xmax]

(range):

  • Within the range, you can move slightly x0

    to:
    • x0 = xmin + dx

      or x0 = xmax - dx

  • For other points, you can refine dx

    (reduce size).

Uniform external interpolation function:



If your interpolated function turns out to be homogeneous outside the interpolation range:

f(x0 < xmin) = f(x0 > xmax) = f_out

      

You can define your interpolated function like this:

f = interp1d(x, y, bound_errors=False, fill_value=f_out)

      

Linear interpolation case:

For the linear case, it would be cheaper to calculate just the difference between the points:

import numpy as np
df = np.diff(y) / np.diff(x)

      

This way you can access them as array components.

0


source







All Articles