import numpy as np
def newton_interpolation_with_table(x, y, xi):
"""
x : array_like, shape (n,)
data points x-coordinates
y : array_like, shape (n,)
data points y-coordinates
xi : scalar
the x value where interpolation is computed
"""
n = len(x)
# Divided difference table
divided_diff = np.zeros((n, n))
divided_diff[:, 0] = y
for j in range(1, n):
for i in range(n - j):
divided_diff[i, j] = (divided_diff[i + 1, j - 1] - divided_diff[i, j - 1]) / (x[i + j] - x[i])
# Print divided difference table
print("Divided Difference Table:")
print(divided_diff)
# Interpolating polynomial
result = divided_diff[0, 0]
product_terms = 1.0
for i in range(1, n):
product_terms *= (xi - x[i - 1])
result += divided_diff[0, i] * product_terms
return result
# Example usage
x = np.array([0.4, 0.5, 0.6, 0.7, 0.8])
y = np.array([-0.916291, -0.693147, -0.510826, -0.356675, -0.223144])
xi = 0.54
print(f"The interpolated value at x = {xi} is {newton_interpolation_with_table(x, y, xi)}")
数值分析第二章习题2,答案是错的。答案如下
用代码算出来和我手算的一样(取前三个点)
Divided Difference Table:
[[-0.916291 2.23144 -2.04115 ]
[-0.693147 1.82321 0. ]
[-0.510826 0. 0. ]]
The interpolated value at x = 0.54 is -0.61531984