MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / gaussian_elimination

Function gaussian_elimination

linear_algebra/gaussian_elimination.py:46–89  ·  view source on GitHub ↗

This function performs Gaussian elimination method Examples: 1. * 1x1 - 4x2 - 2x3 = -2 * 5x1 + 2x2 - 2x3 = -3 * 1x1 - 1x2 + 0x3 = 4 2. * 1x1 + 2x2 = 5 * 5x1 + 2x2 = 5 >>> gaussian_elimination([[1, -4, -2], [5,

(
    coefficients: NDArray[float64], vector: NDArray[float64]
)

Source from the content-addressed store, hash-verified

44
45
46def gaussian_elimination(
47 coefficients: NDArray[float64], vector: NDArray[float64]
48) -> NDArray[float64]:
49 """
50 This function performs Gaussian elimination method
51
52 Examples:
53 1.
54 * 1x1 - 4x2 - 2x3 = -2
55 * 5x1 + 2x2 - 2x3 = -3
56 * 1x1 - 1x2 + 0x3 = 4
57 2.
58 * 1x1 + 2x2 = 5
59 * 5x1 + 2x2 = 5
60
61 >>> gaussian_elimination([[1, -4, -2], [5, 2, -2], [1, -1, 0]], [[-2], [-3], [4]])
62 array([[ 2.3 ],
63 [-1.7 ],
64 [ 5.55]])
65 >>> gaussian_elimination([[1, 2], [5, 2]], [[5], [5]])
66 array([[0. ],
67 [2.5]])
68 """
69 # coefficients must to be a square matrix so we need to check first
70 rows, columns = np.shape(coefficients)
71 if rows != columns:
72 return np.array((), dtype=float)
73
74 # augmented matrix
75 augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1)
76 augmented_mat = augmented_mat.astype("float64")
77
78 # scale the matrix leaving it triangular
79 for row in range(rows - 1):
80 pivot = augmented_mat[row, row]
81 for col in range(row + 1, columns):
82 factor = augmented_mat[col, row] / pivot
83 augmented_mat[col, :] -= factor * augmented_mat[row, :]
84
85 x = retroactive_resolution(
86 augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1]
87 )
88
89 return x
90
91
92if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

retroactive_resolutionFunction · 0.85

Tested by

no test coverage detected