views:

192

answers:

3

help!! i have weird math calculation here. hope someone will explain.

$a = 1.85/100;
$b = 1.5/100;
$c = 1.1/100;
$d = 0.4/100;
$e = 0.4/100;
$f = 0.4/100;
$g = 0.4/100;

$h = $a + $b + $c + $d + $e + $f + $g;

echo $h*100 ."<br>";
$i = $h-$a;
$i = $i-$b;
$i = $i-$c;
$i = $i-$d;
$i = $i-$e;
$i = $i-$f;
$i = $i-$g;

echo $i;

last $i value should be 0 but it returns 6.93889390391E-18

+4  A: 

You should read this article:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Floating point arithmetic is not exact. You should expect small errors. The answer is correct to within a small rounding error. If you need to check if a floating point number is zero it is best not to check that it is exactly equal to zero but instead to check if it is sufficiently close to zero.

If you really need exact arithmetic, don't use floating point types. In your example you could multiply all your numbers by 100 and use integer arithmetic to get an exact answer.

Mark Byers
wow so detail explaination. any idea to correct my equation to show final result 0.00 ?
apis17
Since all your numbers are rational you could do your calculations using rational numbers and get an exact result.
Porges
thank you porges..
apis17
+1  A: 

any idea to correct my equation to show final result 0.00 ?

Yeah, round($i, 2)

The "discrepancies" are usually so small, that rounding it to 2 decimals will almost always solve the problem.

Tor Valamo
thank you.. :) this returns 0..
apis17
use number_format() instead if you want to force it to display two decimals.
Tor Valamo
btw, I see that you're using up to 3 decimals in your calculations, so you should probably round it to 4 in case there's an actual discrepancy..
Tor Valamo
nice info.. is there any performance related problem between round and number_format?
apis17
no, they do the same thing, except number_format returns a string and round returns a float, which in php could be converted to an integer if there is no decimal value.
Tor Valamo
+1  A: 

There is nothing wrong going there, there are simply rounding approximation.

In this very cas you should multiply all your values for 1000 and do a division at the end of the calculation or, better, resort to precise calculation extension

Eineki
nice info eineki. this will help me to be carefull for another calculation. thanks all for great help.
apis17