MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / test_conjugate_gradient

Function test_conjugate_gradient

linear_algebra/src/conjugate_gradient.py:154–173  ·  view source on GitHub ↗

>>> test_conjugate_gradient() # self running tests

()

Source from the content-addressed store, hash-verified

152
153
154def test_conjugate_gradient() -> None:
155 """
156 >>> test_conjugate_gradient() # self running tests
157 """
158 # Create linear system with SPD matrix and known solution x_true.
159 dimension = 3
160 spd_matrix = _create_spd_matrix(dimension)
161 rng = np.random.default_rng()
162 x_true = rng.normal(size=(dimension, 1))
163 b = np.dot(spd_matrix, x_true)
164
165 # Numpy solution.
166 x_numpy = np.linalg.solve(spd_matrix, b)
167
168 # Our implementation.
169 x_conjugate_gradient = conjugate_gradient(spd_matrix, b)
170
171 # Ensure both solutions are close to x_true (and therefore one another).
172 assert np.linalg.norm(x_numpy - x_true) <= 1e-6
173 assert np.linalg.norm(x_conjugate_gradient - x_true) <= 1e-6
174
175
176if __name__ == "__main__":

Callers 1

Calls 2

_create_spd_matrixFunction · 0.85
conjugate_gradientFunction · 0.85

Tested by

no test coverage detected