PHP - Aritmetic operations with floating point

49 Views Asked by At

I need to perform operations with very large numbers like: (-8.3802985809867E + 217 x 4.8047258326981E + 215)

I am programming in PHP a system to solve matrices of linear equations, but being very large numbers it gives me NAN or INF as a result.

I have used the normal module: ($a % $b), also bc_mod and fmod, but neither works for me.

How can I perform operations with very large numbers and also very very small?

1

There are 1 best solutions below

0
jspit On

You can treat mantissa and exponent separately. Code example for a multiplication:

$a = -8.3802985809867E+217;
$b = 4.8047258326981E+215;
$ap = explode('e',sprintf('%0.15e',$a));
$bp = explode('e',sprintf('%0.15e',$b));
$axb = $ap[0]*$bp[0]."e".sprintf('%+d',$ap[1]+$bp[1]);
//"-40.26503707779e+432"

What is used here is simple school math: powers of ten are multiplied by adding the exponents. However, the result cannot be represented as float. In principle, it is better to look for a suitable class / library.