JuniorCodeOccasionalNot answered yet
What does 0.1 + 0.2 == 0.3 print?
Predict the result of this comparison.
print(0.1 + 0.2 == 0.3)
Determine the output and explain.
False. 0.1 + 0.2 is 0.30000000000000004 because these values are not exactly representable in binary floating point, so the sum differs from the literal 0.3. Compare with a tolerance instead — math.isclose(0.1 + 0.2, 0.3).
- ✗Assuming float literals are stored exactly
- ✗Comparing floats with
==instead of a tolerance - ✗Thinking Python uses decimal arithmetic for
floatby default
- →How does
math.isclosedecide whether two floats are equal enough? - →When should you reach for
decimal.Decimalorfractions.Fractioninstead?