in reply to Numeric Comparisons Randomly Giving the Wrong Result
for (my $i = 0; $i<30; $i += 0.1) { print "$i "; }
If you run that, you will notice frequently the numbers ARE NOT an even multiple of 0.1, eg, with 32 bit floats you get "5.9 5.99999999999999 6.09999999999999 6.19999999999999" "22.5 22.6000000000001 22.7000000000001 22.8000000000001", etc. In fact, they are NEVER an even multiple of 0.1, but this is not always clear since there is also a limit to the number of "decimal" places when the number is rendered in non-binary form.
This is not just a perl issue, and there are notorious legends of accounting software disasters because of it; it's why when you are programming applications involving dollars and cents and division, always:
use integer;
Then use cents, not dollars, and remember, this is rounded down -- if you want to include fractions of a cent, decide how many decimal places you need and use that fraction as a base unit. Money is not a floating point measure. It is of fixed precision.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Numeric Comparisons Randomly Giving the Wrong Result
by mjscott2702 (Pilgrim) on Sep 30, 2010 at 13:40 UTC | |
by Corion (Patriarch) on Sep 30, 2010 at 13:43 UTC | |
by mjscott2702 (Pilgrim) on Sep 30, 2010 at 14:19 UTC | |
by Corion (Patriarch) on Sep 30, 2010 at 14:52 UTC | |
by mjscott2702 (Pilgrim) on Sep 30, 2010 at 14:56 UTC | |
by halfcountplus (Hermit) on Sep 30, 2010 at 14:51 UTC | |
by mjscott2702 (Pilgrim) on Oct 01, 2010 at 10:59 UTC |