def delta(k, delta_cache):
if len(delta_cache) <= k:
for _ in range(k - len(delta_cache) + 1):
delta_cache.append([])
for i, val in enumerate(delta_cache[-2][:-1]):
delta_cache[-1].append(delta_cache[-2][i+1] - val)
return delta_cache[k]
def gregory_newton_interpolation(inps, vals, x):
delta_cache = [vals]
assert not any(delta(2, [inps]))
print(delta(0, [[4, 5, 6]]))
gregory_newton_interpolation([1, 2, 3], [2, 3, 4], 1.5)
[4, 5, 6]
def lagrange_interpolation(inps, vals, x):
assert len(inps) == len(vals)
sums = 0
for i, (inp1, val) in enumerate(zip(inps, vals)):
term = 0
num = den = 1
for j, inp2 in enumerate(inps):
if i == j:
continue
num *= (x - inp2)
den *= (inp1 - inp2)
sums += (num / den) * val
return sums
input_arr = [1, 1.2, 1.3, 1.5]
value_arr = [0.368, 0.301, 0.273, 0.223]
lagrange_interpolation(input_arr, value_arr, 1.4)
0.24733333333333346