import numpy as np
import math
import matplotlib.pyplot as plt
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0, 15, 31, 143, 245, 367])
n = len(x)
diff_table = np.zeros((n, n))
diff_table[:,0] = y
for j in range(1, n):
for i in range(n - j):
diff_table[i][j] = diff_table[i + 1][j - 1] - diff_table[i][j - 1]
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
def newton_forward(xp, x, diff_table, h):
u = (xp - x[0]) / h
yp = diff_table[0][0]
for i in range(1, n):
term = diff_table[0][i]
for j in range(i):
term *= (u - j)
term /= factorial(i)
yp += term
return yp
xp = 1.373
h = x[1] - x[0]
yp = newton_forward(xp, x, diff_table, h)
print("Forward Difference Table:")
for i in range(n):
print(f"{x[i]:<5}", end=" ")
for j in range(n - i):
print(f"{diff_table[i][j]:10.4f}", end=" ")
print()
print(f"\nEstimated value: y({xp}) = {yp:.4f}")
plt.plot(x, y, 'o-', label='Original Data')
plt.plot(xp, yp, 'p', label=f'Interpolated Point ({xp}, {yp:.2f})', markersize=10)
plt.xlabel('X')
plt.ylabel('Y')
plt.title("Newton's Forward Interpolation")
plt.grid(True)
plt.legend() Forward Difference Table:
plt.show() 0 0.0000 15.0000 1.0000 95.0000 -201.0000 337.0000
1 15.0000 16.0000 96.0000 -106.0000 136.0000
2 31.0000 112.0000 -10.0000 30.0000
3 143.0000 102.0000 20.0000
4 245.0000 122.0000
5 367.0000