Question

Write a function in Python that solves the linear system ??=? using Gaussian Elimination, taking ?,?...

Write a function in Python that solves the linear system ??=? using Gaussian Elimination, taking ?,? as input. The function should have two phases: the elimination phase, and the back substitution phase. You can use numpy library.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The solution to the above problem is:-

import numpy as np

def f_elimination(A, b, n):
"""
Here we are calculating the forward part of Gaussian elimination.
"""
for row in range(0, n-1):
for i in range(row+1, n):
factor = A[i,row] / A[row,row]
for j in range(row, n):
A[i,j] = A[i,j] - factor * A[row,j]

b[i] = b[i] - factor * b[row]

print('A = \n%s and b = %s' % (A,b))
return A, b

def back_substitute(a, b, n):
""""
Here we are doing back substitution, returns the Gauss result.
"""
x = np.zeros((n,1))
x[n-1] = b[n-1] / a[n-1, n-1]
for row in range(n-2, -1, -1):
sum = b[row]
for j in range(row+1, n):
sum = sum - a[row,j] * x[j]
x[row] = sum / a[row,row]
return x

def gaus(A, b):
"""
This function performs Gauss elimination without pivoting.
"""
n = A.shape[0]

# Check for zero diagonal elements
if any(np.diag(A)==0):
raise ZeroDivisionError(('Division by zero will occur; '
'pivoting currently not supported'))

A, b = f_elimination(A, b, n) # calling f_elimination and storing the result in A,b.
return back_substitute(A, b, n) # Here we are returning the back_substitute result.

# Main program starts here
if __name__ == '__main__':
A = np.array([[9, 3, 5],
[4, -3, -24, ],
[1, 4, -4, ]])
b = np.array([0, 4, 2])
x = gaus(A, b) # calling guassian function and storing the above result in x.
print('Gauss result is x = \n %s' % x)

The output for the above code is:-

- O X 5. CA WINDOWS\SYSTEM32\cmd.exe A = [[ 93 5] [ 0 -4 -26] i 3 -4]] and b = [@ 4 2] A = [[ 935] I -4 -26] [ -23]] and b =

  

Thank you.

Add a comment
Know the answer?
Add Answer to:
Write a function in Python that solves the linear system ??=? using Gaussian Elimination, taking ?,?...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT