From 3a52f4f220c9aecc30f59cc412cbc710d24c0e70 Mon Sep 17 00:00:00 2001 From: schrom01 Date: Thu, 10 Nov 2022 20:57:49 +0100 Subject: [PATCH] implemented Gauss Algorythmus --- Schenk_Brandenberger_S6_Aufg2.py | 75 ++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/Schenk_Brandenberger_S6_Aufg2.py b/Schenk_Brandenberger_S6_Aufg2.py index e69de29..7b03434 100644 --- a/Schenk_Brandenberger_S6_Aufg2.py +++ b/Schenk_Brandenberger_S6_Aufg2.py @@ -0,0 +1,75 @@ +import numpy as np + + +def switchRows(matrix, row1, row2): + matrix[[row1, row2]] = matrix[[row2, row1]] + return matrix + + + +def gaussAltorithmus(A, b): + + def calculateRow(A, b, row, column): + b[row] = [b[row][0] - (A[row][column] / A[column][column]) * b[column][0]] + A[row] = [(A[row][i] - (A[row][column] / A[column][column]) * A[column][i]) for i in range(len(A[row]))] + return A, b + + # Erstelle obere Dreiecksmatrix + columnsToEdit = [] + for row in range(1, len(A)): + columnsToEdit.append(row - 1) + for column in columnsToEdit: + print("Zeile", row, "Spalte", column) + if(A[row-1][column] == 0 and (row - 1 == column)): + rowToSwitch = row + if(row == 1): + while(A[rowToSwitch][column] == 0): + if(len(A) > rowToSwitch + 1): + rowToSwitch += 1 + else: + return "Matrix ist nicht regulär!" + A = switchRows(A, row - 1, rowToSwitch) + b = switchRows(b, row - 1, rowToSwitch) + else: + A, b = calculateRow(A, b, row, column) + + print("\nA\n", A, "\nb\n", b) + + # Rückwärtseinsetzen + columnsToEdit = [] + for row in range((len(A) - 2), -1, -1): + columnsToEdit.append(row + 1) + for column in columnsToEdit: + A, b = calculateRow(A, b, row, column) + print(A) + print(b) + row -= 1 + print("\nA\n", A, "\nb\n", b) + + result = [] + for i in range(len(A)): + result.append(b[i][0] / A[i][i]) + return result + + + +if __name__ == '__main__': + # Beispiel aus Vorlesungsfolen: + A = np.array([[1.0, 5.0, 6.0], + [7.0, 9.0, 6.0], + [2.0, 3.0, 4.0]]) + b = np.array([[29.0], + [43.0], + [20.0]]) + + # A = np.array([[1.0, 1.5, 2.0], + # [2.0, 3.0, 5.0], + # [0.0, 1.0, 2.0]]) + # + # b = np.array([[16.0], + # [35.0], + # [12.0]]) + + result = gaussAltorithmus(A, b) + for i in range(len(result)): + print("x" + str(i) + ": " + str(result[i])) \ No newline at end of file