numpy Python中的部分旋转高斯消元

cgyqldqp  于 2023-04-30  发布在  Python
关注(0)|答案(1)|浏览(140)

我用python中的numpy做了一个高斯消去法的代码。

import numpy as np

A = np.array([[3, -13, 9, 3], [-6, 4, 1, -18], [6, -2, 2, 4], [12, -8, 6, 10]])
b = np.array([-19, -34, 16, 26])

def GaussEliminationPP(A, b):
    n = len(A)
    l = np.arange(n)
    s = np.zeros(n)
    for k in range(n) :
        amax = 0
        for i in range(k, n) :
            a = np.abs(A[l[i],k])
            if a > amax :
                amax = a
                j = i
        l[j], l[k] = l[k], l[j]
        for i in range(k+1, n) :
            xmult = A[l[i],k]/A[l[k],k]
            A[l[i],k] = xmult
            for j in range(k+1, n):
                A[l[i],j] -= xmult*A[l[k],j]
            b[l[i]] -= xmult*A[l[k],j]
        print(A, b)
            

GaussEliminationPP(A, b)

然而,我发现它与解决方案具有不同的价值。我不知道我错在哪里。有人能帮忙吗?提前感谢:)

6l7fqoea

6l7fqoea1#

这里有一个解决方案的例子(你可以自己弄清楚代码的作用,这是我诚实的观点中最好的学习方法):

import numpy as np

def GaussEliminationPP(A, b):
    n = len(A)
    l = np.arange(n)
    s = np.zeros(n)
    for k in range(n):
        amax = 0
        for i in range(k, n):
            a = np.abs(A[l[i],k])
            if a > amax:
                amax = a
                j = i
        l[j], l[k] = l[k], l[j]
        for i in range(k+1, n):
            xmult = A[l[i],k]/A[l[k],k]
            A[l[i],k] = xmult
            for j in range(k+1, n):
                A[l[i],j] -= xmult*A[l[k],j]
            b[l[i]] -= xmult*b[l[k]]
    return A, b

A = np.array([[3, -13, 9, 3], [-6, 4, 1, -18], [6, -2, 2, 4], [12, -8, 6, 10]])
b = np.array([-19, -34, 16, 26])

A_new, b_new = GaussEliminationPP(A.copy(), b.copy())
print("A_new:")
print(A_new)
print("b_new:")
print(b_new)

相关问题