In: Computer Science
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.
Ax = b by Gauss elimination Python function
# importing numpy it use as np
import numpy as np
#function takes inputs a and b
def gaussElimin(a,b):
n = len(b)
# Elimination Phase
#k takes vales 0 to n-1 one by one
for k in range(0,n-1):
#i takes vales k+1 to n one by one
for i in range(k+1,n):
if a[i,k] != 0.0:
lam = a [i,k]/a[k,k]
a[i,k+1:n] = a[i,k+1:n] - lam*a[k,k+1:n]
b[i] = b[i] - lam*b[k]
# Back substitution
for k in range(n-1,-1,-1):
b[k] = (b[k] - np.dot(a[k,k+1:n],b[k+1:n]))/a[k,k]
#return value from this function
return b
Code only ( Python function that solves the linear system
??=? using Gaussian Elimination, taking ?,? as input.)
import numpy as np
def gaussElimin(a,b):
n = len(b)
# Elimination Phase
for k in range(0,n-1):
for i in range(k+1,n):
if a[i,k] != 0.0:
lam = a [i,k]/a[k,k]
a[i,k+1:n] = a[i,k+1:n] - lam*a[k,k+1:n]
b[i] = b[i] - lam*b[k]
# Back substitution
for k in range(n-1,-1,-1):
b[k] = (b[k] - np.dot(a[k,k+1:n],b[k+1:n]))/a[k,k]
return b