
Laurent_R
Veteran
/ Moderator
Jun 2, 2014, 3:43 PM
Post #3 of 4
(8068 views)
|
Although Bill is right and saying the right thing, I think it might be easier to grasp what is going on with the following small test with your data under the Perl debugger:
DB<50> $a = (1.9-1)/0.1; DB<51> printf "%.18f", $a 8.999999999999998224 DB<52> As you can immediately see, the $a variable is not quite 9, but a floating-point number very very very slightly smaller. Now, if I convert that number to an int, this is what you get:
DB<53> print int (sprintf "%.18f", $a); 8 And this is what is going on in your case. $a is converted to an int when you use it in a "foreach(1..$a)" type of construct. And, as Bill said, this is not a bug of foreach, nor a bug of Perl, but this has to do with the way computers store numbers internally (binary format). Generally speaking, a number that is the result of a calculation and can be represented as an integer in decimal notation is not necessarily exactly an integer in binary notation. It might be very slightly smaller in some cases, or very slightly larger in other cases. If you want to see a classical definitive paper on this, read this: http://www.validlab.com/goldberg/paper.pdf. Some things have changed since (64-bit machines, etc.)but the deeper problem with binary versus decimal representation has not. And, BTW, nothing to do with Perl, it is not difficult to display the same type of behavior in an Excel or Open Office spreadsheet.
|