'eq' is a string comparison verses '==' which is numeric. Perl appears to be
applying some rounding when it converts the number to a string before printing.
Make the bottom of you code look like this:
if ($sum1 == $sum2) {
print("EQUAL\n");
}
else {
print("NOT EQUAL\n");
printf "sum1: %30.20f\n", $sum1;
printf "sum2: %30.20f\n", $sum2;
}
The output is this:
sum1 = -237.15
sum2 = -237.15
NOT EQUAL
sum1: -237.15000000000000568434
sum2: -237.14999999999997726263
Read the introduction to chapter 2 of the Perl Cookbook, 2d Ed and recipes 2.2
and 2.3. for idea of how to deal with this.
-----Original Message-----
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf Of
John Deighan
Sent: Sunday, July 24, 2005 3:07 PM
To: [email protected]
Subject: re: comparing floating point numbers
At 02:20 PM 7/24/2005, Ed Chester wrote:
>John Deighan::
> > Is there a safe way to compare 2 floating point numbers in Perl? [snip]
> > My debugger says that they're both '630.24' [snip]
> > However, the == test fails and the != test succeeds
>
>can you post code with the comparison == that fails ?
>if the debugger says they're the same, they're very very probably the same.
>are you sure the variable (or whatever) you're giving to == are
>really what you
>want them to be?
>there are lots of ways to compare numbers, right down to looping over the bits
>and logically
>XNORing them.
Sorry about the lack of sample code, but I know that people who work
with floating point numbers know about this problem, and I was
wondering what the best solution was. Here is sample code with
output. Note that I'm not formatting the output or rounding or
anything - just printing out the contents of the 2 variables.
my $sum1 = -237.15;
my $sum2;
$sum2 += -26.35;
$sum2 += -26.35;
$sum2 += -26.35;
$sum2 += -26.35;
$sum2 += -26.35;
$sum2 += -26.35;
$sum2 += -26.35;
$sum2 += -26.35;
$sum2 += -26.35;
print("sum1 = $sum1\n");
print("sum2 = $sum2\n");
if ($sum1 == $sum2) {
print("EQUAL\n");
}
else {
print("NOT EQUAL\n");
}
OUTPUT:
sum1 = -237.15
sum2 = -237.15
NOT EQUAL
_______________________________________________
Perl-Win32-Users mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
_______________________________________________
Perl-Win32-Users mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs