【国科大——矩阵分析与应用】使用高斯消元法,测试二元一次方程系数产生的误差

使用高斯消元法,测试二元一次方程系数产生的误差

原始方程

{ 47 x + 28 y = 19 89 x + 53 y = 36 \begin{equation} % equation带*之后的意思不整体标号 \begin{cases} 47x +28y=19\\ 89x+53y=36 \end{cases} \end{equation} { 47x+28y=1989x+53y=36

误差来源

对于上述方程组来说,肉眼可解:x=1,y=-1

然而,高斯消元会出现分数 89 47 \frac{89}{47} 4789 。 由于计算机的精度不同,会出现误差,下面测试不同的精度导致使用 高斯消去法 得到的结果不同。

保留有效数字

print(float(format(52.91, '.3g')))  # 保留3位有效数字

代码

import numpy as np
from numpy import *


def Gauss(Mat, Bais, num):
    if (Mat.shape[0] != Mat.shape[1]) or (Mat.shape[0] != Bais.shape[0]):
        raise ValueError("size of matrix doesn't match!")
    A = Mat.copy()
    B = Bais.copy()
    n = A.shape[0]  # n=2
    arg = '.' + str(num) + 'g'
    l_ik = float(format(A[1, 0] / A[0, 0], arg))
    # print(l_ik)

    a1 = float(format(A[0, 0], arg))
    b1 = float(format(A[0, 1], arg))
    a2 = float(format(A[1, 0], arg))
    b2 = float(format(A[1, 1], arg))
    c1 = float(format(B[0, 0], arg))
    c2 = float(format(B[1, 0], arg))
    b2 = float(format(b2 - float(format(l_ik * b1, arg)), arg))
    # print('b2', b2)
    c2 = float(format(c2 - float(format(l_ik * c1, arg)), arg))
    y = float(format(c2 / b2, arg))
    # print(y)
    c1 = float(format(c1 * l_ik, arg))
    b1 = float(format(b1 * l_ik * y, arg))
    # print('b1',b1)
    # print('c1',c1)
    temp = float(format(c1 - b1, arg))
    # print('temp:',temp)
    x = float(format(temp / a2, arg))
    # print('x:',x)
    return [x, y]


if __name__ == '__main__':
    x = np.mat([[47, 28],
                [89, 53]])
    y = np.mat([[19],
                [36]])
    print(Gauss(x, y, 4))

猜你喜欢

转载自blog.csdn.net/qq_44824148/article/details/126634200