Python Program for Lagrange Interpolation Method (with Output)

Table of Contents

This program implements Lagrange Interpolation Formula in Python Programming Language.

In this Python program, x and y are two array for storing x data and y data respectively. Here we create these array using numpy library. xp is interpolation point given by user and output of Lagrange interpolation method is obtained in yp.

Python Source Code: Lagrange Interpolation

# Lagrange Interpolation

# Importing NumPy Library
import numpy as np

# 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))

# Reading data points
print('Enter data for x and y: ')
for i in range(n):
    x[i] = float(input( 'x['+str(i)+']='))
    y[i] = float(input( 'y['+str(i)+']='))

# Reading interpolation point
xp = float(input('Enter interpolation point: '))

# Set interpolated value initially to zero
yp = 0

# Implementing Lagrange Interpolation
for i in range(n):
    p = 1
    for j in range(n):
        if i != j:
            p = p * (xp - x[j])/(x[i] - x[j])
    yp = yp + p * y[i]    

# Displaying output
print('Interpolated value at %.3f is %.3f.' % (xp, yp))

Python Output: Language Interpolation

Enter number of data points: 5
Enter data for x and y: 
Enter interpolation point: 9
Interpolated value at 9.000 is 810.000.