WTF ?

IvorW combobulus at xemaps.com
Wed Jan 10 12:55:34 GMT 2007



> -----Original Message-----
> From: Paul Orrock [mailto:paulo at digitalcraftsmen.net]
> Sent: 10 January 2007 12:39
> To: London.pm Perl M[ou]ngers
> Subject: WTF ?
> 
> 
> I've tried this on a couple of machines running perl 5.8.6 and 5.8.8
> 
> for ($i=1.2;$i<4;$i+=0.05) {
> print $i . "\n";
> }
> 
> Starts off fine, I get
> 
> 1.2
> 1.25
> 1.3 etc
> 
> Suddenly I get
> 
> 3.4
> 3.45
> 3.5
> 3.54999999999999
> 3.59999999999999
> 3.64999999999999
> 3.69999999999999
> 
> Can anyone explain why this is ? I get the correct (in my eyes) 1dp / 
> 2dp result with 0.04 and 0.06 but 0.05 ends up to 14dp ?
> 
Such is the nature of floating point.

Binary fractions (1/2, 1/4, 1/256, etc) are represented exactly. Decimal fractions are not, and are prone to rounding issues.

                                     
This is because FP is held as Mant x 2**exp 


More information about the london.pm mailing list