Re: very simple questions about integer division

  • From: Philipp Kutin <philipp.kutin@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 31 Aug 2012 18:15:43 +0200

On Fri, Aug 31, 2012 at 2:58 PM, Mike Pall <mike-1208@xxxxxxxxxx> wrote:
>   print(-17 % 3)              -->  1   Ick ...
> Actually, LuaJIT has trunc() internally, but it's not exposed as a
> library function. It wouldn't help to fix %, anyway.

I'm somewhat confused what you're referring to in 'fixing' the '%'.
Lua 5.1-ref defines the remainder to be that "of a division that
rounds the quotient towards minus infinity", and that's fine, no?

> Ok, so an extra div() or divmod() function would be the most
> feasible solution (because it can have its own semantics). (...)
> But I'm not sure where I'd place them -- math.* or bit.* are not a
> perfect fit for these functions.

Adding them to the math module seems reasonable to me, since all the
other C-like rounding / float arithmetic functions live there. The
only issue I see is potential clashes with future Lua changes, so
maybe that should be coordinated with Roberto & maintainers?

Also, I'll have to correct myself again: rounding-toward-zero division
can be expressed more succinctly with

c = (a - math.fmod(a,b))/b

since we have remainder-of-divison-rounding-towards-zero. Phew.


Other related posts: