Search code examples
phpmathsubtraction

Subtraction calculation for the same variables differs in different situations


Problem is bit critical. Output I need is 2.9558577807620168e-12.

1#working.php

 <?php 
     $a = 465.90928248188;
     $b = 15.651243716447;
     $c = 450.25803876543; 

     echo $a - $b -$c // output 2.9558577807620168e-12 as expected
 ?>

2#notworking.php

<?php 

     lot of arithmetic calculation almost 200-250 LoC
     $array1_28x1[3]; // 465.90928248188
     $array2_28x1[3]; // 15.651243716447
     $array3_28x1[3]; // 450.25803876543

     echo $array1_28x1[3] - $array2_28x1[3] - $array3_28x1[3];
     // output -4.5474735088646E-13

 ?>

I Don't understand what is the issue. Can it be memory leak? I have done step by step debugging also but could not find any solution. And this is very important calculation so can not even ignore.

Note: There is no changes in the variable's value under those 250 LoC. I have dumped variables before the subtraction.


Solution

  • The problem arises since you display your intermediate variables with only 14 significant digits. This hides 2 additional digits that are present in the original computation but missing in the reconstruction.

    The general solution is to recognize that within the bounds of floating point arithmetic, you have effectively computed zero.

    To get a reconstructable result you could convert the intermediate results to strings which are displayed and then those back to numbers. This will trivially give you results that can be reproduced from the displayed intermediate results.

    As to having a result that is essentially floating point noise and thus represents zero, your scale/magnitude of inputs is 1000, which gives a absolute error scale resp. scale of floating point noise of 1e4*1e-16=1e-12. Both indicated results fall within this scale, i.e., both have to be considered to be zero.