Re: very simple questions about integer division

  • From: Mike Pall <mike-1208@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 31 Aug 2012 14:58:20 +0200

Pierpaolo Bernardi wrote:
> Isn't C division truncation direction undefined, if one argument is negative?

C99 specifies it as truncate towards zero (based on existing
practice). And it fixes the specification of %, too.

Sadly, this is incompatible with the definitions for / and % on
plain Lua numbers:

  print(-17LL / 3LL)          --> -5LL
  print(-17LL % 3LL)          --> -2LL

  print(-17 / 3)              --> -5.6666666666667
  print(math.floor(-17 / 3))  --> -6   \ Well ...
  print(math.ceil(-17 / 3))   --> -5   / you really want trunc() here
  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.

Ok, so an extra div() or divmod() function would be the most
feasible solution (because it can have its own semantics). Another
missing function is a widening multiply that returns both the
lower and upper parts without precision loss. Maybe there are a
couple more integer functions that are easy in C, but expensive to
simulate in Lua.

But I'm not sure where I'd place them -- math.* or bit.* are not a
perfect fit for these functions.


Other related posts: