0

How does it come that the modulo operator in java is different then wolfram alpha?

My formula is:

var = (var-x) % 10

so wolfram gives me the correct result for example

(0 - 1) % 10 = 9

Java gives -1.

How can I fix this the best way?

Jonathan
  • 7,536
  • 4
  • 30
  • 44
user1480139
  • 283
  • 4
  • 16
  • -1 mod 10 = -1 and -1 mod 10 = 9 are both correct – Kuba Spatny Dec 18 '13 at 12:33
  • @Dave It is depending on programming languages according of https://en.wikipedia.org/wiki/Modulo_operation. – MeNa Dec 18 '13 at 12:35
  • Modular arithmetic is sometimes called clock arithmetic because it is circular. So in mod 10, 9 = -1. http://en.wikipedia.org/wiki/Modular_arithmetic – dataNinja124 Dec 18 '13 at 12:35
  • 2
    Note that `%` is the **remainder** operator, not the **modulo** operator. Thought of that way, its behaviour should make sense... – Oliver Charlesworth Dec 18 '13 at 12:41
  • @dataNinja124 If it were a ring, yes (I suppose that's how Wolfram operates). With respect to all integers, my understanding of the operator is different. – Dave Dec 18 '13 at 12:42
  • @Dave a = b mod(c) forms a map from the set of all integers onto a subset of integers that from a ring. So the definition of modulus actually creates a ring. – dataNinja124 Dec 18 '13 at 12:47

4 Answers4

2

That's how % is defined and is supposed to work in most programming languages, even if the opposite would sometimes be useful.

I would suggest implementing your own modulo method:

int positiveModulo(a, b) {
    int result = a % b;
    if (result < 0) { result += b; }
    return result;
}
BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
1

I would write my own mod for that case if needed, something like

public int nonNegativeModOfDiff(int a, int b,int n) {
  int mod = (a-b)%n;
  return mod >= 0 ? mod : mod + n;
}
jcklie
  • 4,054
  • 3
  • 24
  • 42
1

This should do the trick:

class ModTest {
    public static void main (String[] args) {
        int x = -1;
        int m = 10;
        int y = mod(x, m);

        System.out.println(y);
    }

    static int mod(int x, int m) {
        return (x % m + m) % m;
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

From the javaDocs : "It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor."

dataNinja124
  • 130
  • 5