Why can't computers add 0.1 and 0.2? LULucasVDOP 21 Sep, 13:28 Seriously, 0.30000000000000004? How does anything work?
EMEmmaCodes21 Sep, 20:28replies: 1Floats are stored in binary, and 0.1 has no exact binary representation (like 1/3 in decimal). Tiny errors appear. For most science and engineering it doesn't matter; you just format the output. For money, use decimal or integer cents.
Comments 5
Join the discussion CommentAlready have an account? Log in
Floats are stored in binary, and 0.1 has no exact binary representation (like 1/3 in decimal). Tiny errors appear. For most science and engineering it doesn't matter; you just format the output. For money, use
decimalor integer cents.Like 1/3 = 0.333... in decimal. That analogy clicked.
Also never compare floats with
==. Usemath.isclose().math.isclose saved my tests last week.
This happens in every language, not just Python. Try it in JavaScript.