Practice question · Multiple choice
In most languages 0.1 + 0.2 == 0.3 evaluates to false. Why do experienced programmers compare floats with a tolerance instead?
Hints
- Write 1/3 in decimal. Now write 1/10 in binary.
- Ask whether the error appears during the addition or before it.
Show the answer
A. Because 0.1 has no exact binary representation
Why
The error exists before any arithmetic: 0.1 in binary is 0.000110011… repeating, exactly as 1/3 is in decimal. Adding two slightly-wrong numbers gives a slightly-wrong sum that misses the slightly-wrong stored 0.3, which is why money is stored in integer pence and floats are compared within an epsilon.
Practise Variables, Types, and Expressions
The app has 4 more questions on this lesson, and keeps your place in the course. Mathematics I is free to start.
More questions on Variables, Types, and Expressions
- Match each data type to its defining property.
- Order the evaluation steps of the expression 2 + 3 * (8 - 6) / 2.
- Select every statement that is TRUE.
- Because a float stores only finitely many digits, two computations that are mathematically equal can produce…
- In mathematics x = x + 1 is a contradiction with no solution. In most programming languages it is a routine…
- The symbol + adds numbers but joins text. Sort each expression by what + actually does.