in reply to Re: When is a 2 not a 2?
in thread When is a 2 not a 2?
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.
|
|---|