Why is this particular floating point math operation not giving the correct answer?
Why do I get this result?
>>> 0.1 + 0.2 0.30000000000000004
but this works fine?
>>> 0.3 + 0.4 0.7
It has to do with how floats are stored in the hardware. Remember that any number in binary has to be a power of 2, and some decimals cannot be exactly represented that way.
If you need precision, consider using the
decimal (Python 3) module.
Here are some other resources:
- The Python Tutorial » Floating Point Arithmetic: Issues and Limitations
- What Every Computer Scientist Should Know About Floating-Point Arithmetic