linear_algebra: make matrix_inversion doctest deterministic (#15130)

numpy.linalg.inv can return platform-dependent float representations
(e.g. 0.6 vs 0.6000000000000001), which made the doctest fragile across
BLAS/LAPACK backends. Round the results in the doctests so the expected
output is deterministic, and add a second invertible-matrix example.
This commit is contained in:
priya-sundaram-dev
2026-08-31 08:01:50 +02:00
committed by GitHub
parent 64646c5eb9
commit df3a091184
+9 -2
View File
@@ -11,8 +11,15 @@ def invert_matrix(matrix: list[list[float]]) -> list[list[float]]:
Returns:
list[list[float]]: Inverted matrix if invertible, else raises error.
>>> invert_matrix([[4.0, 7.0], [2.0, 6.0]])
[[0.6000000000000001, -0.7000000000000001], [-0.2, 0.4]]
The exact floating-point representation returned by ``numpy.linalg.inv``
can vary slightly across platforms and BLAS/LAPACK backends
(e.g. ``0.6`` vs ``0.6000000000000001``), so the doctests below round the
result to make the expected output deterministic.
>>> [[round(x, 6) for x in row] for row in invert_matrix([[4.0, 7.0], [2.0, 6.0]])]
[[0.6, -0.7], [-0.2, 0.4]]
>>> [[round(x, 6) for x in row] for row in invert_matrix([[1.0, 0.0], [0.0, 2.0]])]
[[1.0, 0.0], [0.0, 0.5]]
>>> invert_matrix([[1.0, 2.0], [0.0, 0.0]])
Traceback (most recent call last):
...