Advertisement
Guest User

Numerical Analysis

a guest
Nov 21st, 2010
2,906
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. #Actual Values: BLACK LINE
  2. #Lagrange Calc: RED LINE
  3. #Vander Calc:   RED "+"
  4.  
  5. #Data used based on example at:
  6.     #http://jayemmcee.wordpress.com/lagrange-polynomial-interpolation/
  7. #Required module Vandermonde can be found at:
  8.     #http://pastebin.com/gWfYcj0W
  9.  
  10. import numpy as np
  11. import Vandermonde as V
  12. import matplotlib as mpl
  13. mpl.use("TKAgg")
  14. import matplotlib.pylab as plt
  15. plt.ion()
  16.  
  17. #Actual function res
  18. R=400
  19. #Num of Interp pts
  20. n=5
  21. #Num of estimated poly plot pts
  22. E=250
  23. #Endpoints
  24. a= -1; b=1
  25. #Function to compare
  26. x = lambda n: np.linspace(a,b,n)
  27. f = lambda x: np.cos(np.sin(np.pi*x))
  28.  
  29. def PolyVander(n,E,x,f):
  30.     data = zip(x(n),f(x(n)))
  31.     Vander = V.VanderInterp(data)
  32.     print "Vander Values:   ",list(Vander)
  33.     return V.toVector(Vander, x(E))
  34.  
  35. plt.clf()
  36. #Actual Values
  37. plt.plot(x(R), f(x(R)), 'k')
  38.  
  39. #Lagrange Coeffs as calculated at:
  40.     #http://jayemmcee.wordpress.com/lagrange-polynomial-interpolation/
  41.  
  42. #c ~ 0.540302305868, for convenience of typing
  43. c = f(0.5)
  44. co = [3, 0, -(16-16*c), 0, (16-16*c)]
  45. co[:] = [i/3.0 for i in co]
  46. Lx = [0.0] * E
  47. for i in xrange(E):
  48.     Lx[i] = co[0] + co[1]*x(E)[i] + co[2]*(x(E)[i])**2
  49.     Lx[i] += co[3]*(x(E)[i])**3 + co[4]*(x(E)[i])**4
  50. plt.plot(x(E), Lx, 'r')
  51. print "Lagrange Values: ",co
  52.  
  53. #Estimated Value
  54.     #Simply to demonstrate that Vandermonde
  55.     #And Lagrange_Pts are same values
  56. plt.plot(x(E),PolyVander(n,E,x,f),'r+')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement