  lua-l archive

• Subject: Re: Problem with integer division in Lua 5.3.1
• From: Daurnimator <quae@...>
• Date: Fri, 8 Jan 2016 09:26:22 +1100

```On 8 January 2016 at 08:23, Hartmut Henkel <hartmut_henkel@gmx.de> wrote:
> On Sat, 28 Nov 2015, Roberto Ierusalimschy wrote:
>
>> > I guess that clears up my misunderstanding, but I still regard an
>> > operation called "integer division" which sometimes returns a result
>> > of type "float" to be counterintuitive.
>>
>> As I explained a few messages ago, the operation is not called integer
>> division. It is called floor division.
>
> Just to report as a caveat, floor division hit me when quickly
> converting a calendar date into a julian date by the formula (Fliegel,
> van Flandern):
>
> jd = d - 32075 + 1461 * (y + 4800 + (m - 14) / 12) / 4 + 367 * (m - 2 -
> (m - 14) / 12 * 12) / 12 - 3 * ((y + 4900 + (m - 14) / 12) / 100) / 4;
>
> This works flawlessly in Fortran and C, with integers. So i thought, in
> Lua assure that variables are integers, then simply replace "/" by "//"
> and the result would be fine. However it wasn't since Lua by "floor
> division" handles negative divisions like (m - 14) / 12 differently from
> the established Fortran and C methods. And it's rather tedious to
> rewrite the simple formula above with Lua's integer facility. Fortran
> seems to do do essentially this:
>
> local idiv = function(a, b)
>   if (a >= 0) and (b >= 0) then return a // b
>   elseif (a >= 0) and (b < 0) then return -(a // (-b))
>   elseif (a < 0) and (b >= 0) then return -((-a) // b)
>   elseif (a < 0) and (b < 0) then return (-a) // (-b)
>   else assert(0)
>   end
> end
>
> More on such cases see also an interesting comparison between languages:
> https://craftofcoding.files.wordpress.com/2013/07/cs_langjuliandates.pdf
>
> (i would have liked Lua to do "//" like Fortran does integer division.)
>
> Regards, Hartmut
>

The wikipedia article on modulo has a good bit on the different types
of division+modulo:
https://en.wikipedia.org/wiki/Modulo_operation#Remainder_calculation_for_the_modulo_operation
The image https://en.wikipedia.org/wiki/Modulo_operation#/media/File:Divmod.svg
is also quite helpful to explain why lua is the way it is.