Skip to content

Commit c15924f

Browse files
committed
Replace array_search with floating-point filter
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`
1 parent 6f5d690 commit c15924f

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/LinearAlgebra/Eigenvector.php

+9-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace MathPHP\LinearAlgebra;
44

5+
use MathPHP\Arithmetic;
56
use MathPHP\Exception;
67
use MathPHP\Exception\MatrixException;
78
use MathPHP\Functions\Map\Single;
@@ -66,8 +67,14 @@ public static function eigenvectors(NumericMatrix $A, array $eigenvalues = []):
6667
foreach ($eigenvalues as $eigenvalue) {
6768
// If this is a duplicate eigenvalue, and this is the second instance, the first
6869
// pass already found all the vectors.
69-
$key = \array_search($eigenvalue, \array_column($solution_array, 'eigenvalue'));
70-
if (!$key) {
70+
$key = false;
71+
foreach (\array_column($solution_array, 'eigenvalue') as $i => $v) {
72+
if (Arithmetic::almostEqual($v, $eigenvalue, $A->getError())) {
73+
$key = $i;
74+
break;
75+
}
76+
}
77+
if ($key === false) {
7178
$ = MatrixFactory::identity($number)->scalarMultiply($eigenvalue);
7279
$T = $A->subtract($);
7380

0 commit comments

Comments
 (0)