0

I have a 1-D data of 100 (x,y) pairs. Let's call the array of x as data_x and the array of y as data_y.

To get f(x):

import numpy as np
from scipy.interpolate import interp1d
f = interp1d(data_x, data_y, bounds_error=False, fill_value=np.nan)

To get f'(x):

def fp(x):
    return (f(x+eps) - f(x))/eps

# where eps is a very small number, for example 1e-3

To get f''(x):

def fpp(x):
    return (fp(x+eps) - fp(x))/eps

To plot, I used the following plot commands:

numpoints = 100
plot_x = np.linspace(-5, 0, numpoints)
plt.plot(plot_x, f(plot_x))
plt.plot(plot_x, fp(plot_x))
plt.plot(plot_x, fpp(plot_x))

When I plot those 3 functions, I get a problematic jaggy line for the second derivative. How do I get rid of these?

enter image description here

ev-br
  • 24,968
  • 9
  • 65
  • 78
Kit
  • 30,365
  • 39
  • 105
  • 149
  • 1
    For straight line interpolation each 'block' will have a constant gradient. The second derivative within each block is therefore zero. It depends what your data is but it seems to measure alternative points at the change in gradient and a second point within the block, which will be zero. – Tls Chris Oct 18 '19 at 18:55

1 Answers1

1

You want a twice differentiable interpolator, use e.g. CubicSpline : CubicSpline(x_data, y_data).derivative(2) is a callable object representing the 2nd derivative. Or if you want the derivative inplace, use CubicSpline(x_data, y_data)(xnew, 2)

ev-br
  • 24,968
  • 9
  • 65
  • 78