Skip to content

fix(matrix): retain Decimal precision for inverse determinants - #15805

Open
lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/decimal-matrix-determinants
Open

lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/decimal-matrix-determinants

Conversation

@lanqing431

Copy link
Copy Markdown

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

The determinant is already computed using Decimal, but converting it to float before the singularity check underflows a small nonzero determinant to zero or overflows a large one to infinity. Valid finite inverses are then rejected or replaced by zeroes.

Keep the determinant as Decimal in both matrix sizes, divide the 2x2 cofactors in Decimal as well, and convert only the final entries to float. Existing doctests are unchanged.

Reproduction / verification

import numpy as np
from matrix.inverse_of_matrix import inverse_of_matrix

for size in (2, 3):
    for scale in (1e-150, 1e150):
        matrix = (np.eye(size) * scale).tolist()
        inverse = inverse_of_matrix(matrix)
        assert np.allclose(np.array(matrix) @ inverse, np.eye(size))

Validated on Windows with CPython 3.15.2:

  • python -m doctest -v matrix/inverse_of_matrix.py
  • python -m pytest matrix/inverse_of_matrix.py --doctest-modules -q
  • python -m ruff check matrix/inverse_of_matrix.py (Ruff 0.17.3)
  • python -m ruff format --check matrix/inverse_of_matrix.py
  • Independent local regression checks: 154 matrices: explicit determinant underflow/overflow cases plus deterministic invertible 2x2 and 3x3 matrices at three scales, checking A @ inverse(A) against the identity.

The regression harness found 54 failing cases on the unchanged upstream file and none after the fix (154 checks). It is kept outside this source-only diff to follow the repository's instruction not to change implementation and doctests together. The original doctests remain unchanged. The complete repository suite and free-threaded CI were not run locally.

Checklist

  • I have read CONTRIBUTING.md and AGENTS.md.
  • This PR only changes one algorithm file.
  • Existing doctests pass and are unchanged.
  • The modified file passes Ruff lint and formatting checks.
  • CI checks have completed. (Not run until this PR is opened.)

AI assistance: OpenAI Codex assisted with source analysis, implementation, reproductions, local verification, and drafting this description.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant