How Does Java Do Modulus Calculations with Negative Numbers

Mod in Java produces negative numbers

The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.

You can find the positive value by doing this:

int i = (((-1 % 2) + 2) % 2)

or this:

int i = -1 % 2;
if (i<0) i += 2;

(obviously -1 or 2 can be whatever you want the numerator or denominator to be)

How does java do modulus calculations with negative numbers?

Both definitions of modulus of negative numbers are in use - some languages use one definition and some the other.

If you want to get a negative number for negative inputs then you can use this:

int r = x % n;
if (r > 0 && x < 0)
{
r -= n;
}

Likewise if you were using a language that returns a negative number on a negative input and you would prefer positive:

int r = x % n;
if (r < 0)
{
r += n;
}

Mod with negative numbers gives a negative result in Java and C

The % operator is treated as a remainder operator, so the sign of the result is the same as that of the dividend.

If you want a modulo function, you can do something like this:

int mod(int a, int b)
{
int ret = a % b;
if (ret < 0)
ret += b;
return ret;
}

Java MOD operator returns negative value

A little hint. If you have unexpected negative value when multiply (or sum) numbers, mostly this is number overflow:

private static int generateNo(int randomNo, int value) {
return (int)(((long)randomNo * value) % 256);
}

Modulus operator incorrect for negative numbers

Mathematicians usually define the remainder when the integer a is divided by the positive integer b to be a - bq, where the quotient q is floor(a ÷ b). According to this definition, the remainder when -3 is divided by 26 is 23 as you rightly say.

However, the Java programming language defines remainder differently. Instead of using floor (i.e. rounding towards negative infinity), the rounding is done towards zero. This doesn't change the answer for positive values, but for negative a and positive b the Java answer is b smaller than the mathematicians' answer (unless b divides exactly into a, in which case everyone agrees the answer is 0). Therefore -3 % 26 == 23 - 26 == -3.

Java programmers usually call % the remainder operator, but you are correct that it is also commonly called the modulus operator. In Visual Basic it's even written Mod, but it works the same as % in C / C# / Java etc.

In my opinion, rounding towards zero rather than negative infinity is a mistake and it only makes life harder. For example, to test if an integer n is odd you ought to be able to do if (n % 2 == 1), but that doesn't work because if n is negative and odd the answer is -1. I don't know which language did it first, but the same mistake has been repeated by C, C++, C# and Java. Languages that do integer division correctly (in my view) include Python, Ruby and Haskell.

In Java 8, methods have been added to the Math class for division where the rounding is towards negative infinity rather than zero. The methods are.

Math.floorDiv(int, int)
Math.floorMod(int, int)
Math.floorDiv(long, long)
Math.floorMod(long, long)

Math.floorMod(-3, 26) returns 23 as you wanted.

Mod operator in java for negative number is not working?

If you want a positive result, you can wrap the mod.

public static int PositiveMod(int value, int mod)
{
return ((value % mod + mod) % mod);
}

int result = PositiveMod(-1, 20); //Returns 19

JavaScript % (modulo) gives a negative result for negative numbers

Number.prototype.mod = function (n) {
"use strict";
return ((this % n) + n) % n;
};

Taken from this article: The JavaScript Modulo Bug

Is there a reason some languages allow a negative modulus?

I doubt that the remainder operator was deliberately designed to have those semantics, which I agree aren't very useful. (Would you ever write a calendar program that shows the weekdays Sunday, Anti-Saturday, Anti-Friday, ..., Anti-Monday for dates before the epoch?)

Rather, negative remainders are a side effect of the way integer division is defined.

A rem B := A - (A div B) * B

If A div B is defined as trunc(A/B), you get C's % operator. If A div B is defined as floor(A/B), you get Python's % operator. Other definitions are possible.

So, the real question is:

Why do C++, Java, C#, etc. use truncating integer division?

Because that's the way that C does it.

Why does C use truncating division?

Originally, C didn't specify how / should handle negative numbers. It left it up to the hardware.

In practice, every significant C implementation used truncating division, so in 1999 these semantics were formally made a part of the C standard.

Why does hardware use truncating division?

Because it's easier (=cheaper) to implement in terms of unsigned division. You just calculate abs(A) div abs(B) and flip the sign if (A < 0) xor (B < 0).

Floored division has the additional step of subtracting 1 from the quotient if the remainder is nonzero.



Related Topics



Leave a reply



Submit