+ 3
Why does 0.1 + 0.2 evaluate to 0.30000000004?
I think I put too many 0's there. Sorry for that. But why does it happen?
4 Answers
+ 4
Such things may happen when manipulating numbers that aren't a sum of powers of two (and I'm including 0.5, 0.25, 0.125, etc.), due to how numbers are stored in memory. Especially when manipulating floats instead of doubles.
http://www.binaryconvert.com/result_float.html?decimal=048046049
http://www.binaryconvert.com/result_float.html?decimal=048046050
See the "most accurate representation" those conversions give? That's an approximation of the value they take in memory when you convert them back to base 10.
The problem still exists with doubles, but to a much lesser degree, as they use twice the memory space compared to floats, allowing for a much higher precision.
+ 4
To explain the problem a bit better:
You know how the fraction 1/3 is 0.3333333... in base 10? In base 3, it would simply be written 0.1.
Here, it's kinda the same situation, we have an infinitely repeating sequence in base 2 (0.00011001100110011...) that is simply written 0.1 in base 10. Hence the inevitable approximation when converting 0.1 to binary to store it in memory.
+ 2
Btw, while upvotes don't really matter for questions, make sure to upvote the best answers, so they appear first.
+ 1
Well, Zen gets an upvote even if they don't matter. I know how some datatypes are stored internally but that's the first time I've seen that site; thanks.