My question for What time is now + X minutes led me to look closer at the modulo math operator, a.k.a mod and denoted %
. (Also the fizzbuzz thread is relevant for this topic.)
To me, modulo has always been one of those “yeeah… it’s something with like division something… who uses this anyway?”. So, I was a bit surprised to find that many consider it to be a basic arithmetic operator, implying one really should be very familiar with its use: After + - * /
there is exponent (^
) - and modulo (%
).
If you’re uncertain of what it actually is, mathematician Donald Knuth defines it as
mod(a, n) = a - n * floor(a / n)
Another way to describe modulo would be as the remainder when dividing number. More about that in a second.
If you’re curious about modulo and why it is worth knowing about, here’s a fun writeup aptly titled Fun with modular arithmetic. It gives a few practical examples and, in the process, introduces some food-for-thought concepts (like “threeven” and “throdd”).
One interesting aspect of modulo is that there apparently is no strict definition how to how to calculate it from negative input! This is frankly astonishing considering how elementary the operation is. It may seem like the above definition should be pretty clear, but apparently not - see the table here!
…and, incidentally, in spite of mod being considered so fundamental, I note we don’t quite have a modulo filter operator in TW! Or, referencing the article about negative number, maybe we do: We have the remainder operator – and close to modulo it indeed is.
For your enjoyment I made the following little thing, i.e a modulo macro using Knuths definition to compare it with TWs remainder op. We can note that their results differ for negative numbers, as outlined in the previously linked comparison table, and we see that the modulo macro joins the ranks of Python and Haskell whereas the TW remainder op behaves like JS along with the majority of listed languages.
\define mod(a, n) {{{ [{!!a}divide{!!n}floor[]multiply{!!n}negate[]add{!!a}] }}}
|a|<$range field=a min="-100" max="100" />|{{!!a}}|
|n|<$range field=n min="-100" max="100"/>|{{!!n}}|
|mod|<<mod>>|
|remainder|{{{ [{!!a}remainder{!!n}] }}}|
BTW, someone competent should probably write a note about modulo in the remainder operator doc tiddler, not least for searchability! If nobody competent steps up, I might just do it and we all suffer the consequences. …it’s something with like division something…