## True modulus

Something you want to see in a LiveCode product? Want a new forum set up for a specific topic? Talk about it here.

Moderators: Klaus, FourthWorld, heatherlaine, robinmiller, kevinmiller

pderocco
Posts: 44
Joined: Fri May 16, 2008 1:26 am

### True modulus

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.
Ciao,
Paul

Lowe
Posts: 2
Joined: Mon May 20, 2019 9:03 pm

### Re: True modulus

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

[-hh]
VIP Livecode Opensource Backer
Posts: 2092
Joined: Thu Feb 28, 2013 11:52 pm
Location: Göttingen, DE

### Re: True modulus

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
``````
shiftLock happens