Skip to content

Commit 9764083

Browse files
committed
Check for floating point in SVD diagonal
If the diagonal has duplicate eigenvalues that are floats, the sort operation can shuffle them around. The strict equivalence then fails when it technically should not. Instead, we can compare the diagonal entries to the sorted entries using `AlmostEqual` with the matrix error for tolerance.
1 parent 9d3c271 commit 9764083

1 file changed

Lines changed: 9 additions & 1 deletion

File tree

  • src/LinearAlgebra/Decomposition

src/LinearAlgebra/Decomposition/SVD.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,15 @@ private static function isDiagonalDescending(NumericMatrix $S): bool
344344
$diagonal = $S->getDiagonalElements();
345345
$sorted = array_values($diagonal); rsort($sorted, SORT_NUMERIC);
346346

347-
return $diagonal === $sorted;
347+
// Compare sorted using matrix error (in case duplicate, floating-point eigenvalues)
348+
$n = count($diagonal);
349+
for ($i = 0; $i < $n; $i++) {
350+
if (!Arithmetic::almostEqual($diagonal[$i], $sorted[$i], $S->getError())) {
351+
return false;
352+
}
353+
}
354+
355+
return true;
348356
}
349357

350358
/**

0 commit comments

Comments
 (0)