Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Simple Math Calculation

Tags:

php

can help me to see this calculation? It suppose echo "equal"... but it give me "not equal"

<?php
$tl_pax = 1;
$ct_pax = 2;
$at_pax = 2;

$a = 0.5;
$b = 0.2;
$c = 0.2;
$d = 0.2;
$e = 0.2;
$f = 0.2;
$g = 0.2;
$h = 0.9;

$sum = $a + $b + $c + $d + ($e * $tl_pax) + ($f * $ct_pax) + ($g * $at_pax) + $h;

$total = 3;

if($total == $sum){
    echo 'equal: ' . $sum . ' - ' . $total;
}
else{
    echo 'not equal: ' . $sum . ' - ' . $total;
}
?>
like image 540
Lucky Avatar asked Nov 24 '25 09:11

Lucky


2 Answers

This is the usual case of the rounding error associated with binary floating point numbers. There are numbers that can't be represented exactly in binary, and thus the result will be of by some margin. To read up on it, the wikipedia article about floating point numbers is great.

The usual pattern found in this case is to pick a delta and compare against it:

 if(abs($total - $sum) < 0.01)
   echo "equal";

You'll have to pick your delta appropiately according to the usecase.

like image 83
Femaref Avatar answered Nov 26 '25 21:11

Femaref


Check if they have difference less than 0.00001

if(abs($total - $sum) < 0.00001){

http://sandbox.phpcode.eu/g/56905/6

This article shows you why is this happening

like image 21
genesis Avatar answered Nov 26 '25 22:11

genesis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!