develooper Front page | perl.perl5.porters | Postings from August 2008

Re: [perl #57950] int(some_expr) sometimes returns different results than some_expr, when result is an integer

Thread Previous
From:
Zefram
Date:
August 15, 2008 17:43
Subject:
Re: [perl #57950] int(some_expr) sometimes returns different results than some_expr, when result is an integer
Message ID:
20080816004334.GI6321@fysh.org
elakin@infohell.net (via RT) wrote:
>looks like some sort of floating-point precision loss,

Certainly is.  32.400451 doesn't have a terminating binary representation.

$ perl -MData::Float=float_hex -lwe 'print float_hex($_),"  ",$_ foreach 32400451, 32.400451*1000000, int(32.400451*1000000)'
+0x1.ee64430000000p+24  32400451
+0x1.ee6442fffffffp+24  32400451
+0x1.ee64420000000p+24  32400450
$

int() truncates, which doesn't mix very well with rounding.  If you
want to round to an integer, do int($x+0.5) or something similar.
If you want exact arithmetic, use Math::BigRat.

-zefram

Thread Previous


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