Gauss elimination using python without using any libraries for a 2d list (n x n) .
Thanks
CODE
def gaussElimination(A, b, n):
l = [0 for x in range(n)]
s = [0.0 for x in range(n)]
for i in range(n):
l[i] = i
max1 = 0.0
for j in range(n):
if abs(A[i][j]) > max1:
max1 = abs(A[i][j])
s[i] = max1
for i in range(n - 1):
max2 = 0.0
for j in range(i, n):
ratio = abs(A[l[j]][i]) / s[l[j]]
if ratio > max2:
max2 = ratio
rindex = j
temp = l[i]
l[i] = l[rindex]
l[rindex] = temp
for j in range(i + 1, n):
multiplier = A[l[j]][i] / A[l[i]][i]
for k in range(i, n):
A[l[j]][k] = A[l[j]][k] - multiplier * A[l[i]][k]
b[l[j]] = b[l[j]] - multiplier * b[l[i]]
x = [0.0 for y in range(n)]
x[n - 1] = b[l[n - 1]] / A[l[n - 1]][n - 1]
for j in range(n - 2, -1, -1):
summ = 0.0
for k in range(j + 1, n):
summ = summ + A[l[j]][k] * x[k]
x[j] = (b[l[j]] - summ) / A[l[j]][j]
print("\nResult = ")
for i in range(n):
print(x[i], end=" ")
matrix = [[11.0, -3.0, 5.0, 2.0], [4.0, 14.0, -1.0, -8.0], [5.0, -2.0, 4.0, 2.0], [1.0, -7.0, 5.0, 19.0]]
vector = [-13.0, -27.0, 20.0, 18.0]
gaussElimination(matrix, vector, 4)
Get Answers For Free
Most questions answered within 1 hours.