# Lagrange interpolation method in Python

# Lagrange interpolation method in Python

### What is Interpolation Method?

Interpolation is the method of finding new data points within an isolated set of known data points. In other words, for any intermediate value of an independent variable, the technique of estimating the value of a mathematical function is interpolation.

Here we can apply the Lagrange Interpolation principle to get our solution.

**Lagrange interpolation principle:**

If y = f (x) takes

y0, y1,…, yn

corresponding to x = x0, x1,…, xn,

This method is preferred over its counterparts, such as Newton's method, because it also applicable for unequal spacing of x.

#### Example 1: Program for Lagrange interpolation method

`Python Code:`

`from math import *`

def lagrange_interpolation(x,y,u):

r = range(len(y))

a = [y[i]/product(x[i]-x[j]for j in r if j!=i)for i in r]

return sum(a[i]*product([u-x[j]for j in r if j!=i])for i in r)

def product(a):

p = 1

for i in a:p*=i

return p

x = [0,1,2,5]

y =[2,3,12,147]

x0 = 2

esti = lagrange_interpolation(x,y,x0)

print("value at x0:",esti)

**Output:**

```
value at x0: 12.0
```

#### Example 2: Program for Lagrange interpolation method

**Python code**

`from math import *`

def lagrange_interpolation(x,y,u):

r = range(len(y))

a = [y[i]/product(x[i]-x[j]for j in r if j!=i)for i in r]

return sum(a[i]*product([u-x[j]for j in r if j!=i])for i in r)

def product(a):

p = 1

for i in a:p*=i

return p

x = [0,2.5,4,5.5,7]

y =[0.0,0.97,1.39,1.70,1.95]

x0 = 4

esti = lagrange_interpolation(x,y,x0)

print("value at x0:",esti)

**Output:**

```
value at x0: 1.39
```