Files
CalWay_Python/89-3.py
2025-06-13 23:08:32 +08:00

73 lines
2.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 列主元高斯消元法
def SovleRowMain(A,b):
ks = 0.00000001
n = len(A)
if len(A[0]) != n:
raise ValueError("A要为方阵")
if len(b) != n:
raise ValueError("b与A的行数不匹配")
p = list(range(n))
for i in range(n):
row_max = abs(A[i][i])
row_max_index = i
for j in range(i + 1, n):
if abs(A[j][i]) > row_max:
row_max = abs(A[j][i])
row_max_index = j
A[i], A[row_max_index] = A[row_max_index], A[i]
b[i], b[row_max_index] = b[row_max_index], b[i]
p[i], p[row_max_index] = p[row_max_index], p[i]
if abs(A[i][i]) < ks:
raise ValueError("A矩阵奇异无法进行高斯消元")
for j in range(i + 1, n):
m = A[j][i] / A[i][i]
A[j][i] = m
for k in range(i + 1, n):
A[j][k] -= m * A[i][k]
b[j] -= m * b[i]
if abs(A[n - 1][n - 1]) < ks:
raise ValueError("A矩阵奇异无法进行高斯消元")
# 回代求解
b[n - 1] /= A[n - 1][n - 1]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
b[i] -= A[i][j] * b[j]
b[i] /= A[i][i]
return b
# 最小二乘法拟合
def LeastSquares(list_x,list_y,n):
m = len(list_x)
x_n = []
b = []
for i in range(2*n+1):
x_n.append(0)
b.append(0)
for j in range(m):
x_n[i]+=(list_x[j]**i)
b[i]+=(list_y[j]*list_x[j]**i)
b = b[:n+1]
A = []
for i in range(n+1):
tmp = []
for j in range(n+1):
tmp.append(x_n[i+j])
A.append(tmp)
print("A:", A)
print("b:", b)
result = SovleRowMain(A, b)
print("result:", result)
return result
#把x和y换成题干的数值###################
x = [19,25,31,38,44]
y = [19.0,32.3,49.0,73.3,97.8]
if __name__ == "__main__":
x_square = [i**2 for i in x]
coeff = LeastSquares(x_square, y, 1)
print("拟合方程: y = %.6f + %.6f*x^2" % (coeff[0], coeff[1]))