A Straw Cut Short by Rounding
A paper straw oboe begins with a small act of optimism: cut a reed, blow steadily, and hope the result sounds less like an irritated duck than a musical instrument. Once it speaks, changing the tube length changes the pitch. Precision matters, though a ruler and a pair of scissors have limits.
Computers have their own limits when representing measurements. Imagine joining two measured lengths of straw, 0.1 metres and 0.2 metres, and checking whether their combined length is exactly 0.3 metres:
const first = 0.1;
const second = 0.2;
const combined = first + second;
console.log(combined.toPrecision(17));
console.log(combined === 0.3);
The output is 0.30000000000000004, followed by false. The surprising part is that the arithmetic is working as designed. JavaScript’s ordinary numbers use binary floating point, and neither 0.1 nor 0.2 has an exact representation in that format. Their stored approximations add up to a value slightly different from the stored approximation of 0.3.
Erlang tells the same story; save this as straw.escript and run it with escript straw.escript:
#!/usr/bin/env escript
main(_) ->
First = 0.1,
Second = 0.2,
Combined = First + Second,
io:format("~.17f~n", [Combined]),
io:format("~p~n", [Combined =:= 0.3]).
Floating-point arithmetic became standardized across much of the industry with IEEE 754 in the 1980s. It gives programs a useful range of magnitudes with predictable rounding, but exact equality can be a poor test for calculated measurements. For a real cutting jig, compare the difference against a tolerance chosen for the tool and the job. Better still, if the jig works in whole millimetres, store 100 and 200 as integers: their sum is exactly 300. Neither representation makes the scissors sharper, but it helps the program describe the cut honestly.