Is my interpretation of the Lagrange polynomial and construction of graph correct?
<pre><code>import matplotlib.pyplot as plt
import matplotlib.pyplot as plt


def f(x):
   return (1 + np.exp(-x)) / (1 + x ** 4)
def lagrange(x, y, x0):
   ret = []
   for j in range(len(y)):
       numerator = 1.0
       denominator = 1.0
       for k in range(len(x)):
           if k != j:
               numerator *= (x0 - x[k])
               denominator *= (x[j] - x[k])
       ret.append(y[j] * (numerator / denominator))
   return ret
plt.plot(x, lagrange(x, f(x), 5), label="Polynom")
plt.plot(x, f(x), label="Function")
plt.legend(loc='upper left')
plt.show()
</code></pre>

<p>I need build graph with original function and with Lagrange polynomial. I newbie to matplotlib library(and to python in general), so i want to confirm that i am right</p>

<p>SciPy has <code>lagrange</code>, here is an example:</p>

<pre><code>import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import lagrange

def f(x):
    return (1 + np.exp(-x)) / (1 + x ** 4)
x = np.linspace(-1, 1, 10)
x2 = np.linspace(-1, 1, 100)
y = f(x)
p = lagrange(x, y)
plt.plot(x, f(x), "o", label="Function")
plt.plot(x2, np.polyval(p, x2), label="Polynom")
plt.legend(loc='upper right')
</code></pre>

<p>the output:</p>

<p><a href="http://i.stack.imgur.com/pkjrT.png" rel="nofollow"><img src="http://i.stack.imgur.com/pkjrT.png" alt="enter image description here"></a></p>

<p>If you want to calculate the interpolated curve by the lagrange formula:</p>

<pre><code>den = x[:, None] - x[None, :]
num = x2[:, None] - x[None, :]

with np.errstate(divide='ignore', invalid='ignore'):
    div = num[:, None, :] / den[None, :, :]

div[~np.isfinite(div)] = 1

y2 = (np.product(div, axis=-1) * y).sum(axis=1)

plt.plot(x, y, "o")
plt.plot(x2, y2)
</code></pre>

<p>The code uses numpy broadcast to speedup the calculation.</p>

python matplotlib