Nomor 1
import numpy as np
class GEPP():
def __init__(self, A, b, doPricing=True): #super(GEPP, self).__init__()
self.A = A self.b = b self.doPricing = doPricing
self.n = None self.x = None
self._validate_input() self._elimination() self._backsub() def _validate_input(self): self.n = len(self.A) if self.b.size != self.n: raise ValueError("Invalid argument: incompatible sizes between" + "A & b.", self.b.size, self.n)
def _elimination(self): # Elimination for k in range(self.n - 1): if self.doPricing: # Pivot maxindex = abs(self.A[k:, k]).argmax() + k if self.A[maxindex, k] == 0: raise ValueError("Matrix is singular.") # Swap if maxindex != k: self.Ak, maxindex = self.Amaxindex, k self.bk, maxindex = self.bmaxindex, k else: if self.A[k, k] == 0: raise ValueError("Pivot element is zero. Try setting doPricing to True.") # Eliminate for row in range(k + 1, self.n): multiplier = self.A[row, k] / self.A[k, k] self.A[row, k:] = self.A[row, k:] - multiplier * self.A[k, k:] self.b[row] = self.b[row] - multiplier * self.b[k]
def _backsub(self): # Back Substitution self.x = np.zeros(self.n) for k in range(self.n - 1, -1, -1): self.x[k] = (self.b[k] - np.dot(self.A[k, k + 1:], self.x[k + 1:])) / self.A[k, k]
def main():
A = np.array([[2., -3., 1., 0.], [-2., 0., 2., 0.], [-0., 0., -1., 0.], [0., 2., -1., -1.]]) b = np.array([[40.], [20.], [40.], [20.]]) print("Matriks Awal") print(A) print("Hasil Matriks Awal") print(b) GaussElimPiv = GEPP(np.copy(A), np.copy(b), doPricing=False) print("Hasil Akhir") print(GaussElimPiv.x) print(GaussElimPiv.A) print(GaussElimPiv.b) GaussElimPiv = GEPP(A, b) print(GaussElimPiv.x)
if __name__ == "__main__":
main()
maka didapatkan hasil
Matriks Awal [[ 2. -3. 1. 0.]
[-2. 0. 2. 0.] [-0. 0. -1. 0.] [ 0. 2. -1. -1.]]
Hasil Matriks Awal [[40.]
[20.] [40.] [20.]]
Hasil Akhir [ -50. -60. -40. -100.] [[ 2. -3. 1. 0.]
[ 0. -3. 3. 0.] [ 0. 0. -1. 0.] [ 0. 0. 0. -1.]]
[[ 40.]
[ 60.] [ 40.] [100.]]
[ -50. -60. -40. -100.] >>>