Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
- import random
- def info_table(x, y):
- df = pd.DataFrame(data={'x_s':[ (x[0] + x[-1])/2,
- np.sqrt(x[0] * x[-1]),
- np.sqrt(x[0] * x[-1]),
- (x[0] + x[-1])/2,
- (2*x[0] * x[-1]) / (x[0] + x[-1]),
- (x[0] + x[-1]) / 2,
- (2 * x[0] * x[-1]) / (x[0] + x[-1])
- ],
- 'y_s':[ (y[0] + y[-1]) / 2,
- np.sqrt(y[0] * y[-1]),
- (y[0] + y[-1]) / 2,
- np.sqrt(y[0] * y[-1]),
- (y[0] + y[-1]) / 2,
- (2 * y[0] * y[-1]) / (y[0] + y[-1]),
- (2 * y[0] * y[-1]) / (y[0] + y[-1])
- ],
- }, 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)'])
- df['y_s*'] = [0 for i in range(len(df))]
- index = np.zeros(len(df))
- for i in range(len(df)):
- k = 0
- while df.iloc[i, 0] > x[k]:
- k += 1
- index[i] = k - 1
- index = index.astype(int)
- df.iloc[:, 2] = y[index[:]] + (y[index[:] + 1] - y[index[:]]) / (x[index[:] + 1] - x[index[:]]) * (df.iloc[:, 0] - x[index[:]])
- df['|y_s-y_s*|'] = [0 for i in range(len(df))]
- df.iloc[:, 3] = abs(df.iloc[:, 1] - df.iloc[:, 2])
- info = f"{df['|y_s-y_s*|'].idxmin()}"
- return (df, info)
- def Least_Squares_Method(type='y=alnx+b'):
- X = np.zeros_like(x)
- Y = np.zeros_like(y)
- if type == 'y=alnx+b':
- for i in range(N):
- X[i] = np.log(x[i])
- Y[i] = y[i]
- elif type == 'y=a/(x+b)':
- for i in range(N):
- X[i] = 1 / x[i]
- Y[i] = y[i]
- else:
- return 0
- sx = 0
- sy = 0
- sx2 = 0
- sxy = 0
- for i in range(N):
- sx += X[i]
- sy += Y[i]
- sxy += X[i] * Y[i]
- sx2 += X[i]**2
- a = ( N * sxy - sx * sy ) / ( N * sx2 - sx**2 )
- b = ( sy * sx2 - sxy * sx ) / ( N * sx2 - sx**2 )
- print(f'a = {a} ; b = {b}')
- return (a, b)
- def f__alogx_b(x):
- return a * np.log(x) + b
- def f__a_divide_x_plus_b(x):
- return a / (x + b)
- def grafic(x, y, type='y=alnx+b'):
- X = np.linspace(x.min() - 0.1 * x.min(), x.max() + 0.1 * x.max(), 100)
- points = np.random.uniform(x.min() - 0.1 * x.min(), x.max() + 0.1 * x.max(), 5)
- if type == 'y=alnx+b':
- Y = f__alogx_b(X)
- points_y = f__alogx_b(points)
- if type == 'y=a/(x+b)':
- Y = f__a_divide_x_plus_b(X)
- points_y = f__a_divide_x_plus_b(points)
- plt.title('Метод найменших квадратів')
- plt.plot(x, y, 'go', label='Початкові дані')
- plt.plot(X, Y, label=f'{info}')
- plt.plot(points, points_y, 'ro', label='Згенеровані дані')
- plt.xlabel('x')
- plt.ylabel('y')
- plt.grid()
- plt.legend()
- plt.show()
- x = np.array([2.9, 3.8, 11.9, 30.1, 66.5, 128])
- y = np.array([0.3, 1.1, 1.9, 3.2, 4.1, 5.2])
- print(f'x = {x}')
- print(f'y = {y}')
- N = len(x)
- table, info = info_table(x, y)
- print(table, '\n')
- print(f"Найкраще підходить функція: {info}")
- a, b = Least_Squares_Method(type=info)
- grafic(x, y, type=info)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement