Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import numpy
  4. import math
  5. import matplotlib.pyplot as plt
  6. from operator import mul
  7. from functools import reduce
  8.  
  9. polynomial_power = 5
  10.  
  11. function = math.sin
  12. function_domain = [0.0, 2.0*math.pi]
  13.  
  14.  
  15. def compute_vandermonde_L_inv(x):
  16. size = (len(x), len(x))
  17. L_inv = numpy.matrix([[0.0 for i in range(size[0])]
  18. for j in range(size[1])])
  19.  
  20. for i in range(size[0]):
  21. for j in range(size[1]):
  22. if i == j == 0:
  23. L_inv.itemset(i, j, 1.0)
  24. elif i < j:
  25. L_inv.itemset(i, j, 0.0)
  26. else:
  27. ks = list(range(i + 1))
  28. del(ks[j])
  29. product_elements = [1.0 / (x[j] - x[k]) for k in ks]
  30. product = reduce(mul, product_elements)
  31. L_inv.itemset(i, j, product)
  32. return L_inv
  33.  
  34. def compute_vandermonde_U_inv(x):
  35. size = (len(x), len(x))
  36. U_inv = numpy.matrix([[0.0 for i in range(size[0])]
  37. for j in range(size[1])])
  38.  
  39. for i in range(size[0]):
  40. for j in range(size[0]):
  41. print(i, j)
  42. if i == j:
  43. U_inv.itemset(i, j, 1.0)
  44. elif j == 0:
  45. U_inv.itemset(i, j, 0.0)
  46. else:
  47. up_left = 0 if i == 0 else U_inv.item(i-1, j-1)
  48. U_inv.itemset(i, j, up_left -\
  49. U_inv.item(i, j-1) * x[j-1])
  50. return U_inv
  51.  
  52.  
  53. # compute N 2d-space points of given function
  54. function_samples_count = polynomial_power + 1
  55. function_samples_x = numpy.linspace(function_domain[0],
  56. function_domain[1], num=function_samples_count)
  57. function_samples_y = [function(x) for x in function_samples_x]
  58.  
  59.  
  60. # solve system of linear equations
  61.  
  62. # convert list of function values to matrix
  63. Y = numpy.matrix([[y] for y in function_samples_y])
  64.  
  65. # decompose Vandermonde matrix to upper right and lower left matrices
  66. # and get their inverse
  67. U_inv = compute_vandermonde_U_inv(function_samples_x)
  68. L_inv = compute_vandermonde_L_inv(function_samples_x)
  69.  
  70. #find coefficients
  71. C = U_inv * L_inv * Y
  72.  
  73. # convert 1-column matrix to list
  74. C = [C.item(i, j) for i in range(C.shape[0]) for j in range(C.shape[1])]
  75.  
  76. # show calculated polynomial coefficients
  77. print('coefficients:', C)
  78.  
  79. # plot
  80. plot_x = numpy.linspace(function_domain[0], function_domain[1], num=1000)
  81. plot_y = [sum([float(c)*(x**p) for c, p in zip(C, range(0, polynomial_power + 1))])
  82. for x in plot_x]
  83.  
  84. plt.plot(function_samples_x, function_samples_y,'--')
  85. plt.plot(plot_x, plot_y)
  86. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement