categorized question
QandAEditors
<p>
You want to compare two floating point numbers and perl complains that they are not equal even though they are equal.
<p>
Sample code:
<code>
$number = 1.80;
$premium = $number * ( 1 + 10/100 ); # 1.8 + 10% of 1.8
$expected = 1.98; # As we know 1.8 + 10% of 1.8 is 1.98
print "Number 1 : $premium \n";
print "Number 2 : $expected \n";
print "Not" if $expected != $premium;
print "Equal !! ";
</code>
<p>
The output is
<code>
Number 1 : 1.98
Number 2 : 1.98
NotEqual !!
</code>
<p>
Well, by now you should be thinking perl is <i>crazy</i>. Let me explain what happens here.
<p>
The floating point numbers are stored in binary format in the computer and even though 10/100 = 0.1 is a finite decimal in base 10 arithmetic, when converted to binary floating point it has to be rounded off at some point. Hence when it is converted back to decimal we will get 0.999999 or .1000001 and not 0.1 as we would expect. So comparing floating point numbers for equality wont give the correct results.
<p>
<b><i>But when I printed the numbers it was showing properly!</i></b>
<p>
This is because while printing the numbers they are rounded off and hence we saw the same numbers even though their internal representation varied by a small fraction.
<p>
<b>Solution:</b>
<p>
While comparing floating point numbers we will have to test for range and not for equality.
<code>
=pod
Sub : isEqualFloat
Desc : to compare two floating point numbers and find out if they are equal
Args : float1, float2, delta value(optinal) or 0.00001
Returns : True if they are apart by the delta value, false otherwise
=cut
sub isEqualFloat($$$)
{
my( $float1, $float2, $delta ) = @_;
$delta ||= 0.00001; # default value of delta
abs( $float1 - $float2 ) < $delta
}
# call as
if ( isEqualFloat( 1.98, ( 1.8 * (1 + 10/100) )) ) {
...
}
# for high precision comparison
if ( isEqualFloat( 1.98, ( 1.8 * (1 + 10/100) ), 0.0000001 ) ) {
...
}
</code>
<p>
<b>For further details, see </b>
<!-- Original:
[http://dlc.sun.com/pdf/800-7895/800-7895.pdf|What Every Computer Scientist Should Know About Floating-Point Arithmetic] (PDF, 240kb)
-->
[http://web.archive.org/web/20080921074325/http://dlc.sun.com/pdf//800-7895/800-7895.pdf|What Every Computer Scientist Should Know About Floating-Point Arithmetic] (PDF, 240kb)
<!-- here's another version, but it's slightly different, and not quite as good.
Let's use the Wayback's copy as long as it's available.
[http://www.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf|What Every Computer Scientist Should Know About Floating-Point Arithmetic] (PDF, 266kb)
-->
</p>
1828