Wednesday, October 7, 2015

Lagrange Interpolation using Python

 Here it is. We could set the order of interpolation by changing the value of k


from pylab import *
from random import uniform
k = 11

def l(t):
    l = []
    for i in arange (len(t)):
        l.append(0.)
        for j in arange(k+1):
            lag = 1.
            for m in arange(k+1):
                if m!=j:
                    lag = lag * (t[i]-x[m])/(x[j]-x[m])
            l[i] = l[i]+y[j]*lag
            

    return l

def f(x):
    f = []
    for i in arange (len(x)):
        f.append(0.)
        f[i] = x[i]+uniform(-10,10)
    return f

x = arange(0.0, 2.0, 0.1)
t = arange(0.,2.,0.001)
y = f(x)
z = l(t)

plot(x,y)
plot(t,z)
xlabel('x')
ylabel('y')
title('interpolasi')
grid(True)
axis([0,2,-111,111])
#savefig("test.png")
show()

.