user1480139
user1480139

Reputation: 383

modulo operator doesn't give the correct result

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?

Upvotes: 0

Views: 195

Answers (4)

dataNinja124
dataNinja124

Reputation: 130

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."

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48713

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;
    }
}

Upvotes: 1

jcklie
jcklie

Reputation: 4094

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;
}

Upvotes: 1

BambooleanLogic
BambooleanLogic

Reputation: 8171

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;
}

Upvotes: 2

Related Questions