Page 1 of 1

True modulus

Posted: Tue Sep 18, 2018 7:40 am
by pderocco
I wish "div" and "mod" didn't produce the results that C produces with / and %. They should have been called something like "quo" and "rem", but it appears that "rem" can be used as a comment. It would be nice to have a pair of built-in operators or functions that produce a modulus that has the same sign as the divisor, and an integral quotient that has the sign of the divisor XORed with the sign of the dividend, so:

Code: Select all

     7 xdiv  4 = 1
     7 xmod  4 = 3
    -7 xdiv  4 = -2
    -7 xmod  4 = 1
     7 xdiv -4 = -2
     7 xmod -4 = -1
    -7 xdiv -4 = 1
    -7 xmod -4 = -3
This should work with floats, so for instance, all of the following should produce a result of 0.1:

Code: Select all

     2.1 xmod 1
     1.1 xmod 1
     0.1 xmod 1
    -0.9 xmod 1
    -1.9 xmod 1
    -2.9 xmod 1
As far as I can tell, this really can't be done without some multi-line conditionals in LiveCode, which is slow and cumbersome.

Re: True modulus

Posted: Fri Jul 05, 2019 9:17 pm
by Lowe
pderocco wrote:
Tue Sep 18, 2018 7:40 am
I wish "div" and "mod" didn't produce the results that C produces with / and %. They should have been called something like "quo" and "rem", but it appears that "rem" can be used as a comment. It would be nice to have a pair of built-in operators or functions that produce a modulus that has the same sign as the divisor, and an integral quotient that has the sign of the divisor XORed with the sign of the dividend, so:
This should work with floats, so for instance, all of the following should produce a result of .1:
As far as I can tell, this really can't be done without some multi-line conditionals in LiveCode, which is slow and cumbersome.
I also wish the same. Hope they can do something.

Regards
Lowe

Re: True modulus

Posted: Sat Jul 06, 2019 3:25 pm
by [-hh]
We have a = (a xdiv b)*b + a xmod b, where
a xmod b = ((a mod b) + b) mod b, or as LC function,

Code: Select all

function xmod a,b
  return ((a mod b) + b) mod b
end xmod
So the following function returns the pair (a xdiv b, a xmod b).

Code: Select all

function xDivMod a,b
  put ((a mod b) + b) mod b into amb 
  return (a-amb)/b,amb -- a xdiv b, a xmod b
end xDivMod