Why is this particular floating point math operation not giving the correct answer?
- addition
- math
- multiplication
- floating-point
- subtraction
- float
- division
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
- floating-point-gui.de
SO dupe: