Subject: | [PATCH] invert returns rubbish rather than reporting matrix is singular |
The inverse of a matrix with determinant zero does not exist. This should be reported one way or another. However, invert() returns some arbitrary matrix in that case, hiding the fact that the given matrix was not actually invertible.
Moreover, the documentation misleadingly suggests that solve() might handle cases of linearly dependent vectors (choosing zero coefficients for free variables, say), although the wording is not quite clear. Anyway, the result of solve() makes no difference whether the equation system(s) were unsolvable, uniquely solvable or had a solution space of positive dimension. Again, for singular matrices some arbitrary vectors from an unfinished sequence of conversion steps will be returned that generally bear no relation whatsoever to the solution space.
A simple remedy could be this patch, changing the documentation to no longer make claims about non-invertible matrices and fixing the code to bail out in such cases rather than silently do nonsense.
Of course it is conceivable to extend the API to actually give useful information about more general cases such as over- or underdetermined linear equation systems. I leave this for the author to decide. It would also be helpful to establish a consistent form of diagnostics -- as of version 0.8, there are cases where methods return undef and others where Math::Matrix just dies. The Carp module or exception objects may be of use here.
-Martin
Subject: | Math-Matrix-0.8-MHASCH-02.patch |
diff -Nrup Math-Matrix-0.8.orig/Matrix.pm Math-Matrix-0.8/Matrix.pm
--- Math-Matrix-0.8.orig/Matrix.pm 2013-09-30 09:40:10.000000000 +0200
+++ Math-Matrix-0.8/Matrix.pm 2015-05-25 01:17:30.000000000 +0200
@@ -133,12 +133,12 @@ matrix. Returns the product or B<undef>
=head2 solve
-Solves a equation system given by the matrix. The number of colums
-must be greater than the number of rows. If variables are dependent
-from each other, the second and all further of the dependent
-coefficients are 0. This means the method can handle such systems. The
-method returns a matrix containing the solutions in its columns or
-B<undef> in case of error.
+Solves an equation system given by the matrix, extended by one or
+more target vectors. The columns exceeding the number of rows are
+taken as target vectors. The matrix must be invertible, so that
+there is a unique solution for each target vector. The method returns
+a matrix containing the solutions in its columns or B<undef> in
+case of error.
=head2 invert
@@ -479,7 +479,7 @@ sub solve {
$try=$i;
# make diagonal element nonzero if possible
while (abs($m->[$i]->[$i]) < $eps) {
- last ROW if $try++ > $mr;
+ return undef if $try++ > $mr;
my $row = splice(@{$m},$i,1);
push(@{$m}, $row);
}