Integer Division has no Integrity

Quick question: In the programming language of your choice, what is -7/2 ?
Depending on your training in that programming language, that answer might surprise you or not; but if you have a somewhat mathematically inclined brain, the answer might irritate you.

If your answer is anything other than

  • -3 (as integer or as untyped constant like in Go)
  • -4 (as integer)
  • -3.5 (as float or similar)
  • -7/2 (as rational type like in very mathematically inclined languages)

you might really consider switching, but my point is, that “-7/2” in itself is, in my mind, not a legal entity with a “have you read the fine print” character; considering eating the half of each of the seven cakes in your overly giant fridge and then having to explain yourself to your significant other. Common scenario.

Now if one somehow might believe, that a division operation on two integers must also be an integer, for consistency reasons or the likes, then

a) that’s plainly wrong™, because integer numbers are a Ring, not a Field:
They are not closed under the operation of division.
b) would that violate the Principle of Least Astonishment, as integer data types are modeled after integer numbers in the real world; natural Mathematics is the domain-specific language to which your code has to adjust in order to qualify for Clean Code.

Now, (b) comes with the caveat that the real -3.5 is a real number and floating-point arithmetics like IEEE 754 cannot exactly resemble that, so unless you really do rational 7/2 arithmetics like e.g. in Lisp or Clojure, the deviation is still there; but this is the difference between some stolen finger tips of buttercream and half a cake, so this is no joke.

My point overall is, that if cleanliness and understandability is one of your goals, you should at least think about what your code is doing and whether most of any possible readers have the exact same model in their mind than you do;
if they do, just write the shortest way possible, if they might not, an additional cast / rounding operation might ground their expectations.

And speaking of resembling the real-world mathematics, I am not even sure whether the rounding convention for negative numbers is taught consistently throughout the world; our school back then went with “round away from zero”, i.e. -7/2 would become -4, which is rather seldom found (quick search tells me: Python 2 or Ruby. Truncating to -3 is cheaper on the hardware, I suppose.
I will now resist the investigation between rigid definition vs. cultural contract.

Anyway. Enjoy your cake 🙂