floating-point rounding error
The tiny inaccuracy in float results caused by storing decimal fractions in binary, such as 0.1 + 0.2 giving 0.30000000000000004.
In more detail
It is not a Python bug; every language using standard binary floats behaves the same. Display with a format specifier, compare with math.isclose(a, b) instead of ==, and use the decimal module or whole numbers of cents for money.
Example
import math
math.isclose(0.1 + 0.2, 0.3) # TrueRelated terms
- floating-point number — A number with a fractional part stored in binary, which can only approximate most decimal values.
- format specifier — The instructions after a colon inside a replacement field, such as .2f for two decimal places, that control how a value is shown.
- round() — The built-in function that rounds a number to a given number of decimal places, returning a new number.
- binary number — The base-two number system, using only the digits 0 and 1, in which computers store all data.
Taught in
- Chapter One In One Sitting — Hands-on Python: Complete Video Course & Book
- A Standard Library Tour — Hands-on Python: Complete Video Course & Book
- Thirty Questions, One Sneaky Print — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Conditions The Exam Loves — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Twelve Traps, One Shape Each — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep