lua-users home
lua-l archive

Re: Problem with integer division in Lua 5.3.1

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


On 2015年11月28日, 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

AltStyle によって変換されたページ (->オリジナル) /