pmmp / Math

PHP library containing math related code used in PocketMine-MP
GNU Lesser General Public License v3.0
41 stars 20 forks source link

Add exception in Math::solveQuadratic() method #53

Closed KygekDev closed 2 years ago

KygekDev commented 3 years ago

Introduction

The Math::solveQuadratic() method accepts parameter $a with the value 0, thus causing it to return array with invalid values (INF, NAN) if $discriminant equal to or larger than 0. Parameter $a should not pass the value 0, because in quadratic equation, coefficient a must not be 0.

Changes

Added an exception in Math::solveQuadratic() method which will be thrown if parameter $a passes the value 0.

Tests

Before adding exception: image

After adding exception: image

SOF3 commented 3 years ago

Very small floats tend to lead to inaccurate results. This is a plot of log(x1), log(x2) against diminishing choices of a with the scale -log(a) (such that a = exp(-X) where X is the x-axis value): image

Magnified image of the orange line without logarithm: image

Mathematically, the asymptote shall converge near -0.40, but starting from 2^-30, the result becomes very unstable and eventually diverges to negative infinity (x2 converges to zero).

What I'm trying to point out is that, while a=0.0 might not mean zero (it might mean a value too small to be represented in IEEE-754-binary64), non-zero values near zero cannot yield any reasonable result anyway.

dktapps commented 3 years ago

A non-zero value is still technically valid regardless of the magnitude.

SOF3 commented 3 years ago

Yes, I was just dismissing my concern when I initially thought that INF/NAN would have been valid because of precision errors. Ends up the quadratic formula messes it up really badly.

KygekDev commented 2 years ago

Thank you.