# Lagrange interpolating polynomials
Given equation:
\begin{align}
f(x) = \frac{1}{1 + 25x^2}
\end{align}


```python
# dependency import
from matplotlib import pyplot as plt
import numpy as np
%matplotlib notebook
```


```python
# functions
def f(x):
    return 1/(1 + 25*(x**2))

def lagrange(x, x_given, i):
    res = 1
    for x_j in x_given[:i] + x_given[i + 1:]:
        res *= (x - x_j) / (x_given[i] - x_j)
    return res

def poly_interpolate(x, x_given, y_given, n, i=0):
    if i + 1 in [len(x_given), n]: return lagrange(x, x_given, i) * y_given[i]
    return lagrange(x, x_given, i) * y_given[i] + poly_interpolate(x, x_given, y_given, n, i + 1)
```


```python
x_given = [-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1]
y_given = [f(x) for x in x_given]
```


```python
plt.plot(np.linspace(-1, 1, num=100), [f(x) for x in np.linspace(-1, 1, num=100)], '--', label='Actual f(x)')
plt.plot(x_given, y_given, 'x', color='red', label='Known f(x)')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.grid()
plt.show()
```


    <IPython.core.display.Javascript object>






## Lagrange Interpolating polynomial


```python
plt.subplots_adjust(hspace=1)
for i in range(1, 9):
    ax = plt.subplot(420 + i)
    ax.plot(np.linspace(-1, 1, num=100), [f(x) for x in np.linspace(-1, 1, num=100)], '--')
    ax.plot(np.linspace(-1, 1, num=100), [poly_interpolate(x, x_given, y_given, i) for x in np.linspace(-1, 1, num=100)])
    ax.plot(x_given, y_given, 'x', color='red', label='Known f(x)')
    plt.title('Polynomial degree is: ' + str(i))
    ax.grid()
plt.show()
```


    <IPython.core.display.Javascript object>






b9d27e6fd4522851814b230360edbf4cb364390c
ipynb
Jupyter Notebook
lagrange_poly.ipynb
BatyaGG/numerical_methods
40036c07ed4db2fb03fe0d188feeb440aa260ce2
MIT
2018-06-23T12:19:55.000Z
2018-06-23T12:19:55.000Z
lagrange_poly.ipynb
BatyaGG/numerical_methods
40036c07ed4db2fb03fe0d188feeb440aa260ce2
MIT
lagrange_poly.ipynb
BatyaGG/numerical_methods
40036c07ed4db2fb03fe0d188feeb440aa260ce2
MIT
Qwen/Qwen-72B
1. YES
2. YES