T
Thens
Hi,
I have a problem comparing floating point numbers. After a lot of googling and docs I found the issue to be because of the internal floating point representation.
Here is a sample program that explains that
#!/usr/local/bin/perl
use strict;
use warnings;
my ( $num, $num1, $num2 );
$num = 1.8;
$num1 = ( $num * (1 + (10/100) ) ); # $num + 10% $num => 1.98
print "Number :", sprintf "%2.20f \n" , $num;
print "Number +10% :", sprintf "%2.20f \n", $num1;
$num2 = 1.98;
print "Number +10% :", sprintf "%30.20f \n", $num2;
if ( $num1 != $num2 ) {
print "FIRST PASS >> $num1 is not equal to $num2 !! \n";
}
if ( ($num1+0.1) != ($num2+.1) ) {
print "SECOND PASS >> $num1 is not eqaul to $num2 !!\n";
}
This prints
FIRST PASS >> 1.98 is not equal to 1.98 !!
I understand this is because of the floating point representation. Then I tried to solve it by adding 0.1 at both the ends and then comparing the numbers. THis seems to have solved the problem. My question is, Is this a reliable solution.
While searching the group archive, I found this can be achieved by checking for a small delta like
$delta = 0.0001
if ( abs ( $num1 - $num2 ) < $delta ) {
# Now they are eual
}
...
I wanted to know under what circumstances may adding 0.1 at both ends can fail.
Thanks and Regards,
Thens.
I have a problem comparing floating point numbers. After a lot of googling and docs I found the issue to be because of the internal floating point representation.
Here is a sample program that explains that
#!/usr/local/bin/perl
use strict;
use warnings;
my ( $num, $num1, $num2 );
$num = 1.8;
$num1 = ( $num * (1 + (10/100) ) ); # $num + 10% $num => 1.98
print "Number :", sprintf "%2.20f \n" , $num;
print "Number +10% :", sprintf "%2.20f \n", $num1;
$num2 = 1.98;
print "Number +10% :", sprintf "%30.20f \n", $num2;
if ( $num1 != $num2 ) {
print "FIRST PASS >> $num1 is not equal to $num2 !! \n";
}
if ( ($num1+0.1) != ($num2+.1) ) {
print "SECOND PASS >> $num1 is not eqaul to $num2 !!\n";
}
This prints
FIRST PASS >> 1.98 is not equal to 1.98 !!
I understand this is because of the floating point representation. Then I tried to solve it by adding 0.1 at both the ends and then comparing the numbers. THis seems to have solved the problem. My question is, Is this a reliable solution.
While searching the group archive, I found this can be achieved by checking for a small delta like
$delta = 0.0001
if ( abs ( $num1 - $num2 ) < $delta ) {
# Now they are eual
}
...
I wanted to know under what circumstances may adding 0.1 at both ends can fail.
Thanks and Regards,
Thens.