by JumpCrisscross · 12y ago · 0 comments
Example, given floats a, b, and c
c = a - b
might result in
c == a
There are volumes of literature related to this.
The short explanation why it is so, is that there is an infinite range of numbers, but we do not have infinite amount of memory, Therefore, to perform operations on very large (or very small) numbers efficiently (on current computer architecture) you need to round things around.
If you do not have time for a degree in maths, then at least go and read this before operating on any instructions on floating point in production code, thanks:
"What Every Computer Scientist Should Know About Floating Point Arithmetic"
http://www.validlab.com/goldberg/paper.pdf
and
>> 3 * 1005.01
=> 3015.0299999999997
This might get truncated to 3015.02 and might >> 3 * 1005.01 * 10000
=> 30150299.999999996
turn into a real loss.A good way to represent this is using Fowler's Quantity pattern:
http://martinfowler.com/eaaDev/quantity.html
That lets you encapsulate the ton of special behavior that money has. For example, for most software money can't be created or destroyed, just transfered.
Now, with proper rounding in the right places, it will all work out. However, what rounding and where is much harder than using fixed point.
As long as it's just addition and subtraction, you'll mostly accumulate small errors -- however, once you multiply or compare numbers, all bets are off.
This is a good article about the subject: http://www.johndcook.com/blog/2009/04/06/numbers-are-a-leaky...
Also, that something is "well-defined" does not imply that is it not a mess. There are quite a few well-defined standards out there that clearly are a mess.
The IEEE-754 standard is not a mess. It is complicated, because it has to be. Extreme care and precision must be taken when talking about mathematical quantities which are neither closed nor associative under the provided operations.
I challenge anyone else to make a concrete standard which supports accurate transcendental operations with numbers which range from 0 to 10^300 while remaining simple and easy to understand.
But sometimes you get the odd significance loss[1] situation.
They might be "well defined" but accurate they are not. In fact the whole point of them is that they are ONLY accurate to some degree.
Moreover, when you do floating point arithmetic, you are not adding the number "0.3" up three times. You are adding an approximation of "0.3" up three times, since 0.3 does not have an exact representation in binary.
What you're saying is akin to saying
"Well, I call 0.3333 + 0.3333 + 0.3333 = 0.9999 <> 1.0 inaccurate in my book."
This is totally accurate, and easier to see because it's in decimal.
The point of them is not that they are accurate to some degree. Floating point numbers have a direct correspondence to a real number. The "problem" is that the reverse is not true, so rounding has to occur.