Code Explanation:
1) from decimal import Decimal
Imports the Decimal class from Python’s decimal module.
Decimal allows arbitrary-precision decimal arithmetic, avoiding floating-point rounding issues.
2) a = Decimal("0.1") + Decimal("0.2")
Decimal("0.1") creates an exact decimal number 0.1.
Decimal("0.2") creates an exact decimal number 0.2.
Adding them gives exactly Decimal("0.3").
So a = Decimal("0.3").
3) b = 0.1 + 0.2
Here, 0.1 and 0.2 are floating-point numbers (float).
Due to binary representation limits, 0.1 and 0.2 cannot be stored exactly.
The result is something like 0.30000000000000004.
So b ≈ 0.30000000000000004.
4) print(a == Decimal("0.3"), b == 0.3)
a == Decimal("0.3") → True, because both are exact decimals.
b == 0.3 → False, because b ≈ 0.30000000000000004 which is not exactly 0.3.
Final Output
True False
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment