Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. import numpy as np
  2. from numpy import linalg as LA
  3. import matplotlib.pyplot as plt
  4. import random
  5.  
  6. #Constants
  7. NODES = 5
  8. DEGREE = 3
  9.  
  10. #Initial and polinom getter functions respectively
  11. func = lambda x: x ** 2 + np.sin(x)
  12. P = lambda x, a: sum([a[i] * float(x ** i) for i in range(0, DEGREE + 1)])
  13.  
  14. #LEAST squares method begin
  15. x = np.array([random.uniform(-1, 1) for i in range(NODES)])
  16. Q = np.full((NODES, NODES), 0, dtype=float)
  17. for i in range(0, NODES):
  18.     for j in range(0, DEGREE + 1):
  19.         Q[i][j] = x[i] ** j
  20. H = Q.T.dot(Q)
  21. y = np.fromiter(map(func, x), float)
  22. b = Q.T.dot(y)
  23. #end
  24. #Dodge from singular case
  25. for i in range(0, NODES):
  26.     for j in range(DEGREE + 1, NODES):
  27.         H[i][j] = i
  28.  
  29. solve = LA.solve(H, b)
  30. #end
  31.  
  32.  
  33. #Lezhandr's method
  34. #Assignation of the multipliers of searchable polinom
  35. cn = np.array([1 / 3, (np.sin(1) - np.cos(1)) * 3, 2 / 3, (28*np.cos(1) - 18 * np.sin(1)) / (2 / 7)])
  36. #end
  37.  
  38.  
  39. #Initial data
  40. a = -1
  41. b = 1
  42. m = 100
  43.  
  44. t = np.arange(a, b + (b - a) / m, (b - a) / m)
  45. s = func(t)
  46. plt.subplot(3, 1, 1)
  47. plt.plot(t, s, '-', lw=2)
  48. plt.title('Plot the legit graph of function')
  49. plt.grid(True)
  50.  
  51. s = [P(x, solve) for x in t]
  52. plt.subplot(3, 1, 2)
  53. plt.plot(t, s, '-', lw=2)
  54. plt.title('Plot the graph of function based on least squares method')
  55. plt.grid(True)
  56.  
  57. s = [P(x, cn) for x in t]
  58. plt.subplot(3, 1, 3)
  59. plt.plot(t, s, '-', lw=2)
  60. plt.title('Plot the graph of function based on Lezhandr\'s polynom')
  61. plt.grid(True)
  62.  
  63. plt.show()
  64.  
  65. s = [func(x) - P(x, cn) for x in t]
  66. plt.subplot(2, 1, 1)
  67. plt.plot(t, s, '-', lw=2)
  68. plt.title('Subtraction plot between the initial function and generalized polynom')
  69. plt.grid(True)
  70.  
  71.  
  72. s = [func(x) - P(x, solve) for x in t]
  73. plt.subplot(2, 1, 2)
  74. plt.plot(t, s, '-', lw=2)
  75. plt.title('Subtraction plot between the initial function and Lezhandr\'s polynom')
  76. plt.grid(True)
  77.  
  78. plt.show()
  79.  
  80. #Computing the total error
  81. integral = 7/5 - np.sin(2) / 2
  82. q2 = [2, 2/3, 2/5, 2/7]
  83. qn = integral - sum([(cn[i] ** 2) * q2[i] for i in range(0, 4)])
  84. print(qn)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement