Skip to content

Commit

Permalink
Check for floating point in SVD diagonal
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Aweptimum committed Dec 4, 2023
1 parent 9d3c271 commit 9764083
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/LinearAlgebra/Decomposition/SVD.php
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,15 @@ private static function isDiagonalDescending(NumericMatrix $S): bool
$diagonal = $S->getDiagonalElements();
$sorted = array_values($diagonal); rsort($sorted, SORT_NUMERIC);

return $diagonal === $sorted;
// Compare sorted using matrix error (in case duplicate, floating-point eigenvalues)
$n = count($diagonal);
for ($i = 0; $i < $n; $i++) {
if (!Arithmetic::almostEqual($diagonal[$i], $sorted[$i], $S->getError())) {
return false;
}
}

return true;
}

/**
Expand Down

0 comments on commit 9764083

Please sign in to comment.