Thread overview
Negative integer modulo/division
Mar 13, 2012
bearophile
Mar 14, 2012
Stewart Gordon
Mar 15, 2012
Caligo
March 13, 2012
When I translate Python code to D I sometimes need in D the different integer division and the different modulo operation of Python3. They give different results with the operands are negative:

Python2 code:

for x in xrange(-10, 1):
    print x, "", x % 3, "", x // 3


Python output:

-10  2  -4
-9  0  -3
-8  1  -3
-7  2  -3
-6  0  -2
-5  1  -2
-4  2  -2
-3  0  -1
-2  1  -1
-1  2  -1
0  0  0



D code:

import std.stdio;
void main() {
    foreach (x; -10 .. 1)
        writeln(x, "  ", x % 3, "  ", x / 3);
}


D output:

-10  -1  -3
-9  0  -3
-8  -2  -2
-7  -1  -2
-6  0  -2
-5  -2  -1
-4  -1  -1
-3  0  -1
-2  -2  0
-1  -1  0
0  0  0



For the modulus I sometimes use:
((x % y) + y) % y

So I suggest to add both simple functions to Phobos, possibly as efficient compiler intrinsics (this means inlined asm).


It seems Ada and CommonLisp have functions for both needs: http://en.wikipedia.org/wiki/Modulo_operation

I have also seen this Wikipedia page doesn't tell (it has a "?") about what % does on floating point values.

Bye,
bearophile
March 14, 2012
On Tue, 13 Mar 2012 15:13:01 -0400, bearophile <bearophileHUGS@lycos.com> wrote:


> For the modulus I sometimes use:
> ((x % y) + y) % y

This might be more efficient (assuming z is your target for this):

if((z = x % y) < 0) z += y;

Though I don't know, maybe the optimizer will reduce to this.

Hard to do it in a single expression without using a function.

-Steve
March 14, 2012
On 14/03/2012 11:27, Steven Schveighoffer wrote:
<snip>
> This might be more efficient (assuming z is your target for this):
>
> if((z = x % y) < 0) z += y;
<snip>

Depends on what you want it to do if y is negative.  In such cases, what you've got here will return a value in (y, 0] if x is positive, or in (2*y, y] if x is negative.

I too wish D gave the choice between floor-mod and trunc-mod.

Stewart.
March 15, 2012
http://www.digitalmars.com/d/archives/digitalmars/D/Could_we_have_mod_in_std.math_152977.html