develooper Front page | perl.perl5.porters | Postings from April 2007

Re: [perl #42260] power-of two differences in minus operation

Thread Previous | Thread Next
From:
Andy Dougherty
Date:
April 9, 2007 12:01
Subject:
Re: [perl #42260] power-of two differences in minus operation
Message ID:
Pine.LNX.4.62.0704091423430.16456@fractal.phys.lafayette.edu
On Sat, 31 Mar 2007, jhh wrote:

> # New Ticket Created by  jhh 
> # Please include the string:  [perl #42260]
> # in the subject line of all future correspondence about this issue. 
> # <URL: http://rt.perl.org/rt3/Ticket/Display.html?id=42260 >
> 
> The minus operator creates strange results for the given example.

Here's a much shorter example that illustrates the same problem.
What you are encountering is the finite resolution of perl's (and C's)
floating point numbers.  If you really require 18-digit accuracy, then
perl's built-in numbers are not the right tool.

You are correct that the exact details of rounding off in the last 
bit have changed between 5.6 and 5.8, but in neither version should they
have been considered reliable.

> Using bignum or bigint does not change the results.

That's odd.  You'll have to show us specifically what you're doing.
It's probably best if you modify the program below and show what you
expect and what you get.  BigInt should work.

#!/usr/bin/perl -w
my $mul = 2**32;
my $a = 104712103;
my $b = 50;
my $c = 449735057880383538;
# For these values, $mul * $a + $b == $c.  Thus $diff should be zero.  
my $diff = $c - ($a * $mul + $b);
printf "Expected: $a $b 449735057880383538 0\n";
printf "Got:      %.0f %.0f %.0f %.0f\n", $a, $b, $c, $diff;

__END__

# Actual output (Solaris/SPARC, 32-bit integers):

$ perl5.6.2 bugreport
Expected: 104712103 50 449735057880383538 0
Got:      104712103 50 449735057880383552 0

$ perl5.8.8 bugreport
Expected: 104712103 50 449735057880383538 0
Got:      104712103 50 449735057880383488 -64

Note too that for both 5.6 and 5.8, the value of $c rendered by
printf "%.0f" is wrong.

-- 
    Andy Dougherty		doughera@lafayette.edu

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About