Ask Uncle Colin: A Modulo Mistake
Dear Uncle Colin,
I wanted to work out: Wolfram|Alpha says it’s 9, but MATLAB says it’s 8. They can’t both be right! What gives? MATLAB Obviously Doesn’t Understand Logical Operations
Hi, MODULO! First up, when computers disagree, the best thing to do is check by hand. Luckily, you don’t have to work out
The quicker way first: you can start from
You might have spotted a pattern as you went through there: the modulos very quickly fell into a cycle of period 3. If you’re sharp, you can spot that
The bigger question, though, is ‘why does MATLAB get it wrong?’. The reason turns out to be the way MATLAB stores numbers. While many languages, when they see an integer, treat it as an integer of arbitrary size, MATLAB sees it as a floating-point number, which has an accuracy of 52 bits. That is, it can only express floating-point numbers accurately if they’re smaller than
-- Uncle Colin
Footnotes:
1. although I suspect that’s what MATLAB is trying to do here