HM1_Aufgabenserie6/Schenk_Brandenberger_S6_Auf...

79 lines
2.4 KiB
Python
Raw Normal View History

2022-11-10 20:57:49 +01:00
import numpy as np
def switchRows(matrix, row1, row2):
matrix[[row1, row2]] = matrix[[row2, row1]]
return matrix
2022-11-10 21:35:17 +01:00
def Schenk_Brandenberger_S6_Aufg2(A, b):
2022-11-10 20:57:49 +01:00
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
2022-11-10 21:35:17 +01:00
countRowSwitch = 0
2022-11-10 20:57:49 +01:00
columnsToEdit = []
for row in range(1, len(A)):
columnsToEdit.append(row - 1)
for column in columnsToEdit:
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)
2022-11-10 21:35:17 +01:00
countRowSwitch += 1
2022-11-10 20:57:49 +01:00
else:
A, b = calculateRow(A, b, row, column)
2022-11-10 21:35:17 +01:00
print("\nObere Dreiecksmatrix A:\n", A, "\nb:\n", b)
2022-11-10 20:57:49 +01:00
# 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)
row -= 1
2022-11-10 21:35:17 +01:00
print("\nA:\n", A, "\nb:\n", b)
2022-11-10 20:57:49 +01:00
2022-11-10 21:35:17 +01:00
det = 1
2022-11-10 20:57:49 +01:00
result = []
for i in range(len(A)):
result.append(b[i][0] / A[i][i])
2022-11-10 21:35:17 +01:00
det *= A[i][i]
if(countRowSwitch % 2 == 1):
det *= (-1)
return result, det
2022-11-10 20:57:49 +01:00
if __name__ == '__main__':
2022-11-10 21:35:17 +01:00
# Beispiel 4.2 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]])
# Beispiel aus Aufgabe 1a
A = np.array([[1.0, 1.5, 2.0],
[2.0, 3.0, 5.0],
[0.0, 1.0, 2.0]])
2022-11-10 20:57:49 +01:00
2022-11-10 21:35:17 +01:00
b = np.array([[16.0],
[35.0],
[12.0]])
2022-11-10 20:57:49 +01:00
2022-11-10 21:35:17 +01:00
result, det = Schenk_Brandenberger_S6_Aufg2(A, b)
print("Ergebnis:")
2022-11-10 20:57:49 +01:00
for i in range(len(result)):
2022-11-10 21:35:17 +01:00
print("x" + str(i) + ": " + str(result[i]))
print("Determinante: " + str(det))