计算方法 | 曲线拟合的最小二乘法
就是找个破多项式,让每个点和真实数据的差值的平方最小,原理就是这么简单。
1.写正则方程组(法方程组)
2.写结果向量
3.解方程组
丢代码:
1 import numpy as np 2 import math 3 # data = eval(input("请输入数据:")) 4 data = [(0.6,7.05),(1.3,12.2),(1.64,14.4),(1.8,15.2),(2.1,17.4),(2.3,19.6),(2.44,20.2)] 5 n = 2 6 m = len(data) 7 fa_mat = [[0 for j in range(n)] for i in range(n)] 8 for i in range(len(fa_mat)): 9 for j in range(len(fa_mat[0])): 10 _sum = 0 11 for k in range(m): 12 _sum += data[k][0] ** (i+j) 13 fa_mat[i][j] = _sum 14 print("法方程组如下:") 15 print(np.array(fa_mat)) 16 # 计算结果向量 17 b = [[0] for i in range(n)] 18 for i in range(n): 19 _sum = 0 20 for k in range(m): 21 _sum += ((data[k][0] ** i) * data[k][1]) 22 # print("_sum += (({} ** {}) * {})".format(data[k][0],i,data[k][1])) 23 b[i][0] = _sum 24 print("结果向量如下:") 25 print(np.array(b)) 26 print("下面是解方程组:\n\n") 27 # 解线性方程组 使用三角分解法 ====================================== 28 mat = fa_mat[:] 29 b = b[:] 30 height = len(mat) 31 width = len(mat[0]) 32 33 # 1 直接分解矩阵 34 # 初始化LU 35 U = [[0 for i in range(width)] for j in range(height)] 36 L = [[0 if i!=j else 1 for i in range(width) ] for j in range(height)] 37 38 print(L,U) 39 40 # 从U第一行开始,对于L来说是从第一列开始 41 for i in range(height): 42 # 依次计算LU的行、列 43 for j in range(i, width): 44 _sum = 0 45 for k in range(i): 46 _sum += L[i][k] * U[k][j] 47 print("U{}{}_sum += L[{}][{}] * U[{}][{}] = {} * {} = {}".format(i,j,i,k,k,j,L[i][k],U[k][j],L[i][k] * U[k][j])) 48 U[i][j] = mat[i][j] - _sum 49 # L的i.j是反着的 50 for j in range(i, width): 51 _sum = 0 52 if j > i: 53 for k in range(i): 54 _sum += L[j][k] * U[k][i] 55 print("L{}{}_sum += L[{}][{}] * U[{}][{}] = {} * {} = {}".format(j,i,j,k,k,i,L[j][k],U[k][i],L[j][k] * U[k][i])) 56 L[j][i] = (mat[j][i] - _sum) / U[i][i] 57 print("L = \n{}".format(np.array(L))) 58 print("U = \n{}".format(np.array(U))) 59 60 print("分解完毕,开始计算Ly=b") 61 # 分解完毕 解Ly =b 62 y = [[0] for i in range(height)] 63 # print(y) 64 for i in range(height): 65 _sum = 0 66 for k in range(i): 67 _sum += L[i][k] * y[k][0] 68 y[i][0] = (b[i][0] - _sum) # 这里不用除以系数因为对角线为1 69 print(y) 70 print("计算完毕,开始计算Ux=y") 71 x = [[0] for i in range(height)] 72 for i in range(height-1,-1,-1): 73 _sum = 0 74 for k in range(height-1,i,-1): 75 _sum += U[i][k] * x[k][0] 76 x[i][0] = (y[i][0] - _sum) / U[i][i] 77 print(x) 78 print("最终结果x: \n{}".format(np.array(x)))
over.
本文来自博客园,作者:Mz1,转载请注明原文链接:https://www.cnblogs.com/Mz1-rc/p/13881006.html
如果有问题可以在下方评论或者email:mzi_mzi@163.com