0% found this document useful (0 votes)
109 views1 page

NM Lab 2 Code

The document presents a Python script that implements Newton's Forward Interpolation method using a set of data points. It constructs a forward difference table to estimate the value of a function at a specified point, and visualizes the original data along with the interpolated point using Matplotlib. The output includes the forward difference table and the estimated value at the given point.

Uploaded by

omshah.nce.080
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views1 page

NM Lab 2 Code

The document presents a Python script that implements Newton's Forward Interpolation method using a set of data points. It constructs a forward difference table to estimate the value of a function at a specified point, and visualizes the original data along with the interpolated point using Matplotlib. The output includes the forward difference table and the estimated value at the given point.

Uploaded by

omshah.nce.080
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

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

You might also like