75 lines
2.2 KiB
Python
75 lines
2.2 KiB
Python
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])) |