Skip to content

Commit f580145

Browse files
author
Release Manager
committed
gh-40493: Euclidean norm crashfix sparse matrices <!-- ^ Please provide a concise and informative title. --> <!-- ^ Don't put issue numbers in the title, do this in the PR description below. --> <!-- ^ For example, instead of "Fixes #12345" use "Introduce new method to calculate 1 + 2". --> <!-- v Describe your changes below in detail. --> <!-- v Why is this change required? What problem does it solve? --> <!-- v If this PR resolves an open issue, please link to it here. For example, "Fixes #12345". --> Fixes #40492. The call to `.norm()` or `norm()` with default parameter (`p = 2` for euclidean norm) crashes for sparse matrices. I go around it by checking if the matrix is sparse and if so, copy it into a dense matrix internally to compute the norm. This must be done since the euclidean norm uses the `.SVD()` method which is not exposed for sparse matrices. ### 📝 Checklist <!-- Put an `x` in all the boxes that apply. --> - [x] The title is concise and informative. - [x] The description explains in detail what this PR is about. - [x] I have linked a relevant issue or discussion. - [x] I have created tests covering the changes. - [ ] I have updated the documentation and checked the documentation preview. ### ⌛ Dependencies <!-- List all open PRs that this PR logically depends on. For example, --> <!-- - #12345: short description why this is a dependency --> <!-- - #34567: ... --> URL: #40493 Reported by: grnx Reviewer(s): grnx, user202729
2 parents 883bc95 + f949fe1 commit f580145

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/sage/matrix/matrix2.pyx

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16484,6 +16484,11 @@ cdef class Matrix(Matrix1):
1648416484

1648516485
sage: matrix(CDF, 2, 2, sparse=True).norm(1)
1648616486
0.0
16487+
16488+
Check the euclidean norm for a sparse matrix (:issue:`40492`)::
16489+
16490+
sage: matrix(ZZ, [[1, 2], [3, 4]], sparse=True).norm()
16491+
5.464985704219043
1648716492
"""
1648816493
from sage.rings.real_double import RDF
1648916494

@@ -16494,8 +16499,11 @@ cdef class Matrix(Matrix1):
1649416499
if p == 2:
1649516500
from sage.rings.complex_double import CDF
1649616501

16497-
A = self.change_ring(CDF)
16498-
A = A.conjugate().transpose() * A
16502+
# Always try to convert to ``dense_matrix`` since sparse matrices
16503+
# don't expose the ``SVD`` method. If the matrix is already dense,
16504+
# the cost is negligible.
16505+
A = self.dense_matrix().change_ring(CDF)
16506+
A = A.conjugate_transpose() * A
1649916507
S = A.SVD()[1]
1650016508
return max(S.list()).real().sqrt()
1650116509

0 commit comments

Comments
 (0)