Skip to content

Commit

Permalink
Replace array_search with floating-point filter
Browse files Browse the repository at this point in the history
array_search seems to fail in most cases when looking for a float in an array of floats. And even if it does find a match, if the key is 0, php evaluates `!0` to true.

To find a match, we can instead loop through and compare the numbers with `Arithmetic::almostEqual` and then explicitly check if `$key === false`
  • Loading branch information
Aweptimum committed Nov 7, 2023
1 parent 32f8bff commit 163c0f9
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/LinearAlgebra/Eigenvector.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace MathPHP\LinearAlgebra;

use MathPHP\Arithmetic;
use MathPHP\Exception;
use MathPHP\Exception\MatrixException;
use MathPHP\Functions\Map\Single;
Expand Down Expand Up @@ -66,8 +67,14 @@ public static function eigenvectors(NumericMatrix $A, array $eigenvalues = []):
foreach ($eigenvalues as $eigenvalue) {
// If this is a duplicate eigenvalue, and this is the second instance, the first
// pass already found all the vectors.
$key = \array_search($eigenvalue, \array_column($solution_array, 'eigenvalue'));
if (!$key) {
$key = false;
foreach (\array_column($solution_array, 'eigenvalue') as $i => $v) {
if (Arithmetic::almostEqual($v, $eigenvalue, $A->getError())) {
$key = $i;
break;
}
}
if ($key === false) {
$Iλ = MatrixFactory::identity($number)->scalarMultiply($eigenvalue);
$T = $A->subtract($Iλ);

Expand Down

0 comments on commit 163c0f9

Please sign in to comment.