
In mathematics, 0.1 plus 0.2 is exactly 0.3. With ordinary Python floating-point arithmetic, however, the result often appears as 0.30000000000000004, and an exact comparison with 0.3 returns false. The addition rule is fine. The inputs were already approximated when stored.
Common floating-point formats store binary fractions. The decimal value 0.1 has an endlessly repeating binary expansion, so a finite machine representation must choose a nearby value. The same happens separately to 0.2 and 0.3. Adding the stored approximations introduces another rounding step; the resulting stored number can differ from the one obtained by entering 0.3 directly. The display may shorten long decimal expansions, making two values look equal even when their exact stored forms differ.
There are three levels to keep apart: the mathematical value, its finite machine representation and what appears on screen. Measurements can be compared within a suitable tolerance. When exact decimal amounts matter, dedicated decimal arithmetic or an integer representation is more appropriate. This is a limit of representation, not a reason to distrust every computer calculation.
Source: https://docs.python.org/3/tutorial/floatingpoint.html
Discover more from Geoffrey Chen
Subscribe to get the latest posts sent to your email.