2021-08-02
import numpy as np
# ys: y-coordinates
# x: any value between 0 and len(ys) - 1
def cubic_query(ys, x):
n = ys.shape[0]
if x < 0 or x > n-1:
raise ValueError('value x must be between 0 and n-1')
if x == 0.0: return ys[0]
elif x == float(n-1): return ys[-1]
start = np.floor(x)
x -= start
prev = int(start) - 1
follow = int(start) + 2
p0 = ys[prev if prev >= 0 else 0]
p1 = ys[int(start)]
p2 = ys[int(start)+1]
p3 = ys[follow if follow < n else n-1]
f0 = p1
f1 = p2
df0 = (p2 - p0) / 2
df1 = (p3 - p1) / 2
a = 2*f0 - 2*f1 + df0 + df1
b = -3*f0 + 3*f1 - 2*df0 - df1
c = df0
d = f0
return a*x**3 + b*x**2 + c*x + d
Watch the video: