高斯消除矩陣

staHuri發表於2018-11-09
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#

def pprint(A):
    for i in A:
        print(i)

    print("")


data = [
    [1, 2, 1, 2],
    [3, 8, 1, 12],
    [0, 4, 1, 2]
]

n = len(data)
print("輸入資料")
pprint(data)

for i in range(n):

    print("第{}次操作".format(i))
    maxE = abs(data[i][i])
    # 最大值在第幾行
    maxRow = i
    for k in range(i + 1, n):
        if abs(data[k][i] > maxE):
            maxE = abs(data[k][i])
            maxRow = k

    # 當前行交換最大的行
    for k in range(i, n + 1):
        data[maxRow][k], data[i][k] = data[i][k], data[maxRow][k]
    print("當前行交換最大的行 交換結果")
    pprint(data)

    # 改0
    for k in range(i + 1, n):
        c = -data[k][i] / data[i][i]
        print(-data[k][i] ,"/", data[i][i])
        for j in range(i, n + 1):
            if i == j:
                data[k][j] = 0
            else:
                data[k][j] += c * data[i][j]
    print("改0結果")
    pprint(data)

# 化簡後結果
print("化簡結果")
pprint(data)

# 結果計算
result = [0 for i in range(n)]
for i in range(n - 1, -1, -1):
    result[i] = data[i][n] / data[i][i]
    for k in range(i - 1, -1, -1):
        data[k][n] -= data[k][i] * result[i]

print(result)

相關文章