lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Thu, Feb 9, 2017 at 6:18 AM, Martin <> wrote:

So at least six different variants possible. Which one you prefer and why?

The division and modulo operations should come in pairs so that 

D = d “ (D div d) + (D mod d)

The two obvious candidates for div are floor and truncate. Lua chooses floor. Common Lisp provides floor, truncate, ceiling, and round, with corresponding quotients and remainders.

Folks interested in this topic should take a look at "The Euclidean Definition of the Functions div and mod" by Raymond T. Boute, University of Nijmegen, ACM Transactions on Programming Languages and Systems, Vol 14, No. 2, April 1992. Its abstract:

The definitions of the functions div and mod in the computer science literature and in programming languages are either similar to the Algol or Pascal definition (which is shown to be an unfortunate choice) or based on division by truncation (T-definition) or division by flooring as defined by Knuth (F-definition). The differences between various definitions that are in common usage are discussed, and an additional one is proposed, which is based on Euclid’s theorem and therefore is called the Euclidean definition (E-definition). Its distinguishing feature is that 0 <= D mod d < abs(d) irrespective of the signs of D and d. It is argued that the E- and F-definitions are superior to all other ones in regularity and useful mathematical properties and hence deserve serious consideration as the standard convention at the applications and language level. It is also shown that these definitions are the most suitable ones for describing number representation systems and the realization of arithmetic operations at the architecture and hardware level.