Skip to content

Fix transpose_tridiagonal_matrix for non-symmetric matrices - #498

Merged
domokane merged 1 commit into
FinancePy-Org:masterfrom
mokshupadhyay:fix/transpose-tridiagonal-matrix
Dec 4, 2026
Merged

domokane merged 1 commit into
FinancePy-Org:masterfrom
mokshupadhyay:fix/transpose-tridiagonal-matrix

Conversation

@mokshupadhyay

Copy link
Copy Markdown
Contributor

transpose_tridiagonal_matrix in financepy/utils/math.py transposes a tridiagonal matrix stored as three columns (row i holds A[i,i-1], A[i,i], A[i,i+1]). It swapped the sub- and super-diagonal columns but did not shift them by one row, which a transpose needs (A.T[i,i-1] = A[i-1,i] and A.T[i,i+1] = A[i+1,i]). The result is wrong for any matrix that is not symmetric.

Real result for the 4x4 matrix with rows [0,2,3], [4,5,6], [7,8,9], [10,11,0], expanded to a dense matrix, on master and with this change:

true transpose  [[2,4,0,0], [3,5,7,0], [0,6,8,10], [0,0,9,11]]
master          [[2,0,0,0], [6,5,4,0], [0,9,8,7], [0,0,0,11]]     (not equal)
after           [[2,4,0,0], [3,5,7,0], [0,6,8,10], [0,0,9,11]]     (equal)

The fix keeps the diagonal and fills the sub-diagonal from the previous row's super-diagonal, and the super-diagonal from the next row's sub-diagonal.

Test: test_transpose_tridiagonal_matrix in tests/unit/test_model_finite_difference.py compares the result with the transpose of the dense matrix; it fails on master and passes now. The only caller I found is fd_roll_forwards in financepy/models/finite_difference.py (and I did not find anything calling fd_roll_forwards), so if that function is considered dead code this is a fix to a public helper only. I did not run the whole unit suite myself: the worker that prepared this saw two unrelated failures in test_inflation_swap.py that fail the same way on untouched upstream, and I did not repeat that. math.py uses CRLF line endings and I kept them.

The function only swapped the sub- and super-diagonal columns. In the
(sub, diag, super) row layout A.T[i,i-1] = A[i-1,i] and
A.T[i,i+1] = A[i+1,i], so the diagonals must also shift by one row.
The result was wrong whenever the matrix is not symmetric.

Add a test comparing against the dense transpose.
@domokane
domokane merged commit 4f9a125 into FinancePy-Org:master Dec 4, 2026
1 of 2 checks passed
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.

2 participants