Skip to content

Whole numbers and precision

How to get a whole number and a remainder, and what to expect from fractions

mediumYou need: op: arithmetic

Ordinary division gives a fraction, and that is not always what is wanted: items come one at a time, tiles are whole, a link index is whole. op has operations of its own for whole numbers.

tick 0
Operation0
=
Operation1
=
Operation2
=
Operation3
=
Operation4
=
Operation5
=
@counter0number
exactnullnull
wholenullnull
restnullnull
downnullnull
signnullnull
alwaysnullnull
Operation In the block What it computes 7 and 2 −7 and 2
div / ordinary division 3.5 −3.5
idiv // integer division 3 −4
mod % remainder 1 −1 (with −7 and 3)
emod %% unsigned remainder 1 2 (with −7 and 3)

Two numbers in that table are worth remembering, because they surprise people.

idiv does not drop the fractional part, it rounds down. For positives those are the same thing; for negatives they are not: −3.5 rounds down to −4, not to −3. If dropping is what you want, take the absolute value, divide, and restore the sign separately.

The sign of mod’s remainder follows the sign of the dividend. The remainder of −7 divided by 3 is −1, not 2. For an “always non-negative” remainder there is a separate operation, emod: it gives 2.

tick 0
Operation0
=
Operation1
=
Operation2
=
@counter0number
downnullnull
upnullnull
closernullnull

floor rounds down, ceil up, round to the nearest whole number. A half goes up with round: 2.5 becomes 3, not 2. For negatives “down” means “further from zero”: floor of −3.2 gives −4.

None of the three has a second field: they round one number.

tick 0
Operation0
=
Operation1
=
Operation2
=
@counter0number
sumnullnull
samenullnull
strictnullnull

The sum of 0.1 and 0.2 is 0.30000000000000004, and that is not a bug in mlog. Numbers are stored the way they are almost everywhere — as binary fractions — and 0.1 in binary is endless, like ⅓ in decimal. A tail in the seventeenth digit always remains.

The interesting part is different: equal still answers “equal”. Comparing numbers in mlog is not exact but has a tolerance of 0.000001: anything closer counts as the same. That is exactly why arithmetic with fractions usually behaves the way you expect.

strictEqual (labelled === on the button) knows no tolerance and answers “not equal”: it compares values exactly.

Unofficial fan project, not affiliated with Anuke. Mindustry sprites, fonts and translations © Anuke, used under GPL-3.0; Fira Code under OFL-1.1. Site code is GPL-3.0.