Check if matrix is singular doing inverse (#49)

* Check if matrix is singular doing inverse

* add return bool type
This commit is contained in:
Povilas Susinskas 2017-02-15 11:09:16 +02:00 committed by Arkadiusz Kondas
parent a33d5fe9c8
commit f0a7984f39
3 changed files with 34 additions and 0 deletions

View File

@ -21,4 +21,12 @@ class MatrixException extends \Exception
{
return new self('Column out of range');
}
/**
* @return MatrixException
*/
public static function singularMatrix()
{
return new self('Matrix is singular');
}
}

View File

@ -233,6 +233,10 @@ class Matrix
throw MatrixException::notSquareMatrix();
}
if ($this->isSingular()) {
throw MatrixException::singularMatrix();
}
$newMatrix = [];
for ($i = 0; $i < $this->rows; ++$i) {
for ($j = 0; $j < $this->columns; ++$j) {
@ -271,4 +275,12 @@ class Matrix
return new self($newMatrix, false);
}
/**
* @return bool
*/
public function isSingular() : bool
{
return 0 == $this->getDeterminant();
}
}

View File

@ -141,6 +141,20 @@ class MatrixTest extends TestCase
$matrix->inverse();
}
/**
* @expectedException \Phpml\Exception\MatrixException
*/
public function testThrowExceptionWhenInverseIfMatrixIsSingular()
{
$matrix = new Matrix([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]);
$matrix->inverse();
}
public function testInverseMatrix()
{
//http://ncalculators.com/matrix/inverse-matrix.htm