Python Program to Generate Forward Difference Table

Table of Contents

In numerical analysis, method like Newton's Forward Interpolation relies on Forward Difference Table.

In this program, we are going to generate forward difference table in Python programming language.

Python Source Code: Forward Difference Table


# Reading number of unknowns
n = int(input('Enter number of data points: '))

# Making numpy array of n & n x n size and initializing 
# to zero for storing x and y value along with differences of y
x = np.zeros((n))
y = np.zeros((n,n))


# Reading data points
print('Enter data for x and y: ')
for i in range(n):
    x[i] = float(input( 'x['+str(i)+']='))
    y[i][0] = float(input( 'y['+str(i)+']='))
    
# Generating forward difference table
for i in range(1,n):
    for j in range(0,n-i):
        y[j][i] = y[j+1][i-1] - y[j][i-1]

        
print('\nFORWARD DIFFERENCE TABLE\n');

for i in range(0,n):
    print('%0.2f' %(x[i]), end='')
    for j in range(0, n-i):
        print('\t\t%0.2f' %(y[i][j]), end='')
    print()

Python Output: Forward Difference Table

Enter number of data points: 5
Enter data for x and y: 
x[0]=40
y[0]=31
x[1]=50
y[1]=73
x[2]=60
y[2]=124
x[3]=70
y[3]=159
x[4]=80
y[4]=190

FORWARD DIFFERENCE TABLE

40.00	31.00	42.00	9.00	-25.00	37.00
50.00	73.00	51.00	-16.00	12.00
60.00	124.00	35.00	-4.00
70.00	159.00	31.00
80.00	190.00