MarkBaker / PHPMatrix

PHP Class for handling Matrices
MIT License
1.42k stars 13 forks source link

New Exception Subclass For Determinant=0 #15

Closed oleibman closed 3 years ago

oleibman commented 3 years ago

I am continuing to work on breaking up PhpSpreadsheet MathTrig, and have arrived at the matrix functions. I believe it would be helpful if the "arithmetic" exception (failing inverse when determinant is 0, which should result in a NAN error) were to throw a more descriptive exception than others (matrix not square, containing non-arithmetic data, etc., which should result in a VALUE error). Hence, I have added MatrixDiv0Exception as an extension of MatrixException.

It is true that I can get by without this change, by querying the Exception message. That approach does not seem as clean as a separate Exception subclass.

I considered a separate exception for "not square", which turns up in a number of different places. I don't think I would need this distinction for PhpSpreadsheet, but could easily add it if you feel it might be useful.

The code for Division and Multiplication needed minor improvements. Division wrapped its inverse call in a try/catch, throwing "determinant non-zero" for catch. But, it might err in a different way, if the matrix contains a non-numeric value, or if it's not square. I think it should suffice to just let any exception be passed up the line, without even trying to catch it.

Multiplication implicitly throws an error for non-numeric values. It is changed to explicitly throw an exception. I suspect there are probably other problems of this ilk; I am not attempting to be comprehensive.

The exception message for Inverse has been changed to be consistent with Division.

oleibman commented 3 years ago

Added another push to allow Identity matrix to be generated with zeros instead of nulls. This would simplify PhpSpreadsheet Munit function.