Advertisement
999ms

lab4

Dec 13th, 2019
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4. xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
  5. ys = [5, 6, 8, 10, 12, 13, 12, 10, 8, 10, 8, 11, 7, 9, 11, 10, 9, 12, 11, 6]
  6.  
  7. gx = []
  8. gy = []
  9. t = []
  10. deg = 6
  11.  
  12. for k in range(deg):
  13.     t.append(0)
  14.     for i in range(len(xs)):
  15.         t[k] += ys[i] * xs[i] ** k
  16.  
  17. t = np.array(t)
  18.  
  19.  
  20. def get_matrix():
  21.     res = np.zeros((deg, deg))
  22.     for k in range(deg):
  23.         for i in range(len(xs)):
  24.             for d in range(deg):
  25.                 res[k][d] += xs[i] ** (d + k)
  26.     return res
  27.  
  28.  
  29. a = np.linalg.solve(get_matrix(), t)
  30.  
  31.  
  32. def f(x):
  33.     res = 0
  34.     for i in range(len(a)):
  35.         res += a[i] * x ** i
  36.     return res
  37.  
  38.  
  39. for i in range(len(xs)):
  40.     print(ys[i], f(xs[i]))
  41.  
  42. gx = []
  43. gy = []
  44.  
  45. x = xs[0]
  46. deltaX = 0.01
  47.  
  48. while x <= xs[-1]:
  49.     gx.append(x)
  50.     gy.append(f(x))
  51.     x += deltaX
  52.  
  53. fig, ax = plt.subplots()
  54. ax.plot(gx, gy, color='green')
  55. ax.scatter(np.array(xs), np.array(ys), color='red')
  56.  
  57. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement