Advertisement
mirosh111000

ІДЗ№9

Jun 1st, 2023
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.55 KB | None | 0 0
  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import random
  5.  
  6. def info_table(x, y):
  7. df = pd.DataFrame(data={'x_s':[ (x[0] + x[-1])/2,
  8. np.sqrt(x[0] * x[-1]),
  9. np.sqrt(x[0] * x[-1]),
  10. (x[0] + x[-1])/2,
  11. (2*x[0] * x[-1]) / (x[0] + x[-1]),
  12. (x[0] + x[-1]) / 2,
  13. (2 * x[0] * x[-1]) / (x[0] + x[-1])
  14. ],
  15. 'y_s':[ (y[0] + y[-1]) / 2,
  16. np.sqrt(y[0] * y[-1]),
  17. (y[0] + y[-1]) / 2,
  18. np.sqrt(y[0] * y[-1]),
  19. (y[0] + y[-1]) / 2,
  20. (2 * y[0] * y[-1]) / (y[0] + y[-1]),
  21. (2 * y[0] * y[-1]) / (y[0] + y[-1])
  22. ],
  23. }, index=['y=ax+b', 'y=ax^b', 'y=alnx+b', 'y=ab^x', 'y=a/(x+b)', 'y=1/(ax+b)', 'y=x/(ax+b)'])
  24. df['y_s*'] = [0 for i in range(len(df))]
  25.  
  26. index = np.zeros(len(df))
  27. for i in range(len(df)):
  28. k = 0
  29. while df.iloc[i, 0] > x[k]:
  30. k += 1
  31. index[i] = k - 1
  32. index = index.astype(int)
  33.  
  34. df.iloc[:, 2] = y[index[:]] + (y[index[:] + 1] - y[index[:]]) / (x[index[:] + 1] - x[index[:]]) * (df.iloc[:, 0] - x[index[:]])
  35. df['|y_s-y_s*|'] = [0 for i in range(len(df))]
  36. df.iloc[:, 3] = abs(df.iloc[:, 1] - df.iloc[:, 2])
  37. info = f"{df['|y_s-y_s*|'].idxmin()}"
  38. return (df, info)
  39.  
  40. def Least_Squares_Method(type='y=alnx+b'):
  41.  
  42. X = np.zeros_like(x)
  43. Y = np.zeros_like(y)
  44.  
  45. if type == 'y=alnx+b':
  46. for i in range(N):
  47. X[i] = np.log(x[i])
  48. Y[i] = y[i]
  49.  
  50. elif type == 'y=a/(x+b)':
  51. for i in range(N):
  52. X[i] = 1 / x[i]
  53. Y[i] = y[i]
  54.  
  55. else:
  56. return 0
  57.  
  58.  
  59. sx = 0
  60. sy = 0
  61. sx2 = 0
  62. sxy = 0
  63. for i in range(N):
  64. sx += X[i]
  65. sy += Y[i]
  66. sxy += X[i] * Y[i]
  67. sx2 += X[i]**2
  68.  
  69. a = ( N * sxy - sx * sy ) / ( N * sx2 - sx**2 )
  70. b = ( sy * sx2 - sxy * sx ) / ( N * sx2 - sx**2 )
  71. print(f'a = {a} ; b = {b}')
  72.  
  73. return (a, b)
  74.  
  75. def f__alogx_b(x):
  76. return a * np.log(x) + b
  77.  
  78. def f__a_divide_x_plus_b(x):
  79. return a / (x + b)
  80.  
  81. def grafic(x, y, type='y=alnx+b'):
  82.  
  83. X = np.linspace(x.min() - 0.1 * x.min(), x.max() + 0.1 * x.max(), 100)
  84. points = np.random.uniform(x.min() - 0.1 * x.min(), x.max() + 0.1 * x.max(), 5)
  85.  
  86. if type == 'y=alnx+b':
  87. Y = f__alogx_b(X)
  88. points_y = f__alogx_b(points)
  89.  
  90. if type == 'y=a/(x+b)':
  91. Y = f__a_divide_x_plus_b(X)
  92. points_y = f__a_divide_x_plus_b(points)
  93.  
  94.  
  95. plt.title('Метод найменших квадратів')
  96. plt.plot(x, y, 'go', label='Початкові дані')
  97. plt.plot(X, Y, label=f'{info}')
  98. plt.plot(points, points_y, 'ro', label='Згенеровані дані')
  99. plt.xlabel('x')
  100. plt.ylabel('y')
  101. plt.grid()
  102. plt.legend()
  103. plt.show()
  104.  
  105.  
  106.  
  107. x = np.array([2.9, 3.8, 11.9, 30.1, 66.5, 128])
  108. y = np.array([0.3, 1.1, 1.9, 3.2, 4.1, 5.2])
  109.  
  110. print(f'x = {x}')
  111. print(f'y = {y}')
  112.  
  113. N = len(x)
  114. table, info = info_table(x, y)
  115. print(table, '\n')
  116. print(f"Найкраще підходить функція: {info}")
  117.  
  118. a, b = Least_Squares_Method(type=info)
  119. grafic(x, y, type=info)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement