Computer systems store information in a binary format. CPUs (and some languages) use different methods of encoding floating point numbers.
Usually a floating point number has a much larger range than an integer. For instance, my perl binary stores a floating point number as a C double, which is of a sytem dependend size, but on my machine (Linux / AMD Atlon XP), that means 8 bytes.
Given that a floating point number on my machine has a range of about (some handwaving here...) -1.8e+308 to 1.8e+308, and that it is impossible to even store all the integers in that range in 8 bytes, some trickery is used when storing those numbers.
Most implementations store the number using an algorithm like this: first, the number is split up in 3 parts:
This design has some complications, though: most obviously, you only have as much precision as the number of bits in the mantissa. This also means that you can (and usually will) lose precision by doing aritmatic on floating point numbers.my $value = ($sign ? 1 : -1) * $mantissa * ( 2 ** $exponent);
There's more complications here, but I can't find the docs on them now, and anyway I'm getting a headache trying to think about binary numbers between 0 and 1, so let's leave it at this, and just state the (hopefully) by now obvious:
Use rounding when printing floating points, so you won't get bit (as often) by all of this
Whether you want to use the rounded numbers in calculations too is more or less dependent on what sort of calculations you are doing (and the type of rounding).
Hope this helps,
Joost.
Update:kesterkester++ for pointing to the docs. perlnumber has all the gory details.
In reply to Re: weird print behavior
by Joost
in thread weird print behavior
by anjiro
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |