0
votes

I'm trying to interpolate a simple function with a cubic spline using scipy. I have instructions to use a 0.0001 space grid (thus the design of v) and to use 5 evenly spaced knots.

def h(x):
    if -2 < x < 0:
        return (x+0.5)**2
    elif 0 < x < 2:
        return (x-0.5)**2

h = np.vectorize(h)

v = np.linspace(-2,2,num=40000)
knots = np.linspace(-1.999, 1.9999, 5)
tck_h = interpolate.splrep(v, h(v), t=knots)
result_ip_h = interpolate.splev(v, tck_h)

However, tck (the tuple that is returned by interpolate.splrep) seems to be returning both more knots (some repeated) and several "nans" for coefficients:

(array([-2.000000e+00, -2.000000e+00, -2.000000e+00, -2.000000e+00,
        -1.999000e+00, -9.992750e-01,  4.500000e-04,  1.000175e+00,
         1.999900e+00,  2.000000e+00,  2.000000e+00,  2.000000e+00,
         2.000000e+00]),
 array([nan, nan, nan, nan, nan, nan, nan, nan, nan,  0.,  0.,  0.,  0.]),
 3)

I thought maybe 40000 points at x was too much but reducing that wasn't a problem. Maybe it's a problem with the function h?

1

1 Answers

0
votes

I modified the implementation of the h function. The problem seems to be that the function was not defined everywhere, therefore returning NaN values (actually None values)...

import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate

def h(x):
    if x < 0:
        return (x+0.5)**2
    else:
        return (x-0.5)**2

h = np.vectorize(h)

v = np.linspace(-2, 2, num=500)


knots = np.linspace(-1.999, 1.999, 5)
tck_h = interpolate.splrep(v, h(v), t=knots)
result_ip_h = interpolate.splev(v, tck_h)

plt.plot(v, h(v), label='h');
plt.plot(v, result_ip_h, label='spline'); plt.legend();