Floating Point issue in Programming Languages

|
| By Webner

When we pass a floating point value to a variable, then the value which we store in the variable is not the actual value but it is something approximately near to that number which transfers to that variable.

Let us understand this by a PHP example:

<?php<
$x=0.1;
Echo $x; // Output will be 0.1
Echo number_format($x,30); // Output will be 0.100000000000000005551115123126
?>

And during all arithmetic computations, exact number (which is 0.100000000000000005551115123126 in above case) is used by the computer.

For example:

<?php
$x = 0.1;
$total_amount = 0;
for($i=0;$i<10;$i++) //this loop will add 0.1 with 0, 10 times to make it 1.
{
    $total_amount += $x;
}
echo number_format($total_amount,30)." - ".$total_amount.":<br>";
// Now according to our thinking $total_amount will have value 1 because 0.1 is added to it 10 times
// but it is not true because $x didn’t have the exact value 0.1 during computation
if($total_amount == 1)  // this condition will fail because $total_amount is having the value
//0.999999999999999888977697537484 which is not equal to 1 and the
//control goes to else case.
{
echo "compared equal";
}
else
{
echo "did not compare as equal, actual value is: ";
echo number_format($total_amount,30);
}

Solution:

if(round($total_amount,2) == 1) //Now the the condition will true and the control goes to if case.
{
echo "compared equal";
}
else
{
echo "not equal";
}

Leave a Reply

Your email address will not be published. Required fields are marked *