"""
【问题描述】根据N个数据点构造最小二乘多项式拟合。
【输入形式】在屏幕上依次输入数据点的个数N,和N对数据点的x和y座标。
【输出形式】输出最小二乘多项式和误差。
"""import numpy as np
defls_poly(x, y):
n =len(x)
f = np.zeros((n,3), dtype=np.float)for i inrange(3):
f[:, i]= x**i # 初始化f
a = np.transpose(f)@f
b = np.transpose(f)@y
c = np.linalg.inv(a)@b
c = np.flipud(c)return c
defmain():
n =int(input())
x = np.zeros(n, dtype=np.float)# 初始化x, y
y = np.zeros(n, dtype=np.float)for i inrange(n):# 输入x, y
p, q =map(float,input().split())
x[i]= p
y[i]= q
c = ls_poly(x, y)print(c)
sumz =0
z =0for i inrange(3):
z += c[i]*x**(2-i)for i inrange(n):
sumz +=(z[i]-y[i])**2
sum1 = np.sqrt(sumz)# 求误差print('%.7f'% sum1)if __name__ =='__main__':
main()
最小二乘法
"""
【问题描述】根据N个数据点构造最小二乘拟合直线y=ax+b。
【输入形式】在屏幕上依次输入数据点的个数N,和N对数据点的x和y座标。
【输出形式】输出最小二乘拟合直线y=ax+b和误差。
"""import numpy as np
defls_line(x, y):
xm = np.mean(x)# 求x,y均根
ym = np.mean(y)
sum_x =(x - xm) @ (x - xm)
sum_xy =(y - ym) @ (x - xm)# 解方程
a = sum_xy / sum_x # 求出a
b = ym - a * xm # 根据y=a*x+b;求出breturn a, b
defmain():
n =int(input())
x = np.zeros(n, dtype=np.int)# 初始化x, y
y = np.zeros(n, dtype=np.int)for i inrange(n):# 输入x, y
p, q =map(int,input().split())
x[i]= p
y[i]= q
a, b = ls_line(x, y)print('y=', end='')print('%.7f'% a, end='')print('x+', end='')print('%.7f'% b)
sumz =0
z = x * a + b - y
for i inrange(n):
sumz += z[i]**2
sum1 = np.sqrt(sumz)# 求误差print('%.7f'% sum1)if __name__ =='__main__':
main()