in reply to When is a 2 not a 2?

I tryd this script and realized that is the serious error.
I modified yours script and it seem to me that float == integer do not work properly.
my $x; for ($x=1.0; $x <= 3.0; $x += 0.2) { print "$x\n"; } print "Stop: x=$x\n"; print "No, x is not 3.\n" if $x != 3.0;
This is perl, v5.10.0 built for MSWin32-x86-multi-thread (with 1 registered patch, see perl -V for more detail)
Binary build 1001 283495 provided by ActiveState http://www.ActiveState.com

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

    It has nothing to do with floats being compared to integers. In fact, you're comparing floats with floats.

    >perl -e"use Devel::Peek; Dump(3.0)" SV = NV(0x184968c) at 0x225318 <-- NV = float REFCNT = 1 FLAGS = (PADBUSY,PADTMP,NOK,READONLY,pNOK) NV = 3

    Also, it has nothing to do with Perl or Windows. Were you to write the same thing in C or BASIC, you'd get the same results.

    #include <stdio.h> int main() { double x; for (x=1.0; x <= 3.0; x += 0.2) { printf("%lf\n", x); } printf("Stop: x=%lf\n", x); if (x != 3.0) { printf("No, x is not 3.\n"); } return 0; }
    1.000000 1.200000 1.400000 1.600000 1.800000 2.000000 2.200000 2.400000 2.600000 2.800000 Stop: x=3.000000 No, x is not 3.

    2/10th is also a periodic number in binary. It would take an infinite amount of storage to store it and an infinite amount of time to process it. There is some precision loss.

    If you were to print the entire number instead of rounding it (which numerical stringification does), you'd find that you're comparing 3.0000000000000004 to 3.0.

    Update: Added C code.