Dear Uncle Colin,
I wanted to work out 341mod13: 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 341 by hand and then divide it by 13 to find the remainder 1. Instead, there’s a quicker way and a much quicker way.

The quicker way first: you can start from 30=1 and continually multiply by 3, casting out 13s, until you reach 341mod13: it starts (all the following modulo 13) 313; 329; 331; 343; 359; 361; … 3403 and 3419mod13, as Wolfram|Alpha says.

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 339mod13=(33)131mod13, meaning 341=339×329mod13.

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 252 4.5×1015. That’s between 333 and 334, so 341 gets messed up because it’s too big for MATLAB to store sensibly.

-- Uncle Colin

Footnotes:

1. although I suspect that’s what MATLAB is trying to do here