Advertisement
Guest User

Numerical Analysis

a guest
Nov 21st, 2010
8,119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def LagrangeInterp(data, x):
  4.     #Number of data points
  5.     n=len(data)
  6.     #Number of x points
  7.     nx = len(x)
  8.  
  9.     #Parse x, y data points
  10.     dx = [d[0] for d in data]
  11.     dy = [d[1] for d in data]
  12.  
  13.     #Allocate space for L(x)
  14.     L = [0.0]*(nx)
  15.  
  16.     def b(j,xi):
  17.         """Calculate b_j(x_xi)"""
  18.         v = 1.0
  19.         for k in xrange(n):
  20.             if k != j:
  21.                 v *= (xi-dx[k]) / (dx[j]-dx[k])
  22.         return v
  23.  
  24.     #Construct L(x)
  25.     for i,xi in enumerate(x):
  26.         #Construct each element of L(x)
  27.         for j in xrange(n):
  28.             L[i] += dy[j]*b(j,xi)
  29.            
  30.     return L
  31.  
  32. if '__main__' in __name__:
  33.     import matplotlib as mpl
  34.     mpl.use("TKAgg")
  35.     import matplotlib.pylab as plt
  36.     plt.ion()
  37.     x = lambda n: np.linspace(-1,1,n)
  38.     f = lambda x: np.cos(np.sin(np.pi*x))
  39.     plt.plot(x(300),f(x(300)),'k')
  40.     n=5
  41.     LX=x(250)
  42.     data=zip(x(n),f(x(n)))
  43.     LY = LagrangeInterp(data, LX)
  44.     plt.plot(LX,LY,'r')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement