WTF ?

Sue Spence virtualsue at pennine.com
Wed Jan 10 13:42:36 GMT 2007


Paul Orrock wrote:
> [Floating point abuse snipped]
> 
> Can anyone explain why this is ? I get the correct (in my eyes) 1dp / 
> 2dp result with 0.04 and 0.06 but 0.05 ends up to 14dp ?

This is a FAQ from the dawn of computer science. There will be many 
responses on why it doesn't work. What does work is forgetting all about 
using floating point in computed loops (those involving an 
increment/decrement), and stick to looping over integers and lists.

There are useful fudges for lightweight purposes, e.g. to display all 
numbers in the range between 1.2 and 4 with an increment of 0.5, 
multiply all the parameters by 100 and divide at the end, using s/printf 
as necessary to get a tidy result:

for ($i = 120; $i < 400; $i+=5) {
   printf "%.2f\n", $i/100;
}




More information about the london.pm mailing list