in reply to When is a 2 not a 2?

This is real (pardon the pun) interesting. I thought: they have missed the obvious, use int. Wrong:
my $x; for ($x=1; int($x) <= 2; $x += 0.1) { print "$x\n"; } print "Stop: x=$x\n"; print "No, x is not 2.\n" if $x != 2;
Gives:
1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 Stop: x=3 No, x is not 2.
So then I RTFM on int.
Changing the comparisons to text (the comparison operators stringify both sides) the result is correct, but of course this is not a solution for numbers greater than 9.

Replies are listed 'Best First'.
Re^2: When is a 2 not a 2?
by ikegami (Patriarch) on Jan 31, 2008 at 10:24 UTC

    int(2.1) is 2, which is <= 2, so the loop won't end then like it should. This is a completely different bug than the OP's.

    You were maybe thinking something more along the lines of int($x*10)/10 <= 2, but that would only work with some combination of numbers. int($x*10+0.5)/10 <= 2 might be ok, but you'd still be needlessly accumulating error in your variable.

    As already mentioned (although not in so many words), if you want to loop a certain number of times, count the number of loops passes and derive the decimal number from the loop pass number.