views:

1464

answers:

5

In JavaScript the % operator seems to behave in a very weird manner. I tried the following:

>>> (0 - 11) % 12
-11

Why does it return -11 instead of 1 (as in Python)?

I am sure I am doing or expecting something wrong, but the docs don't tell me what.

+5  A: 

It's just a difference between languages, in how they define modulus/remainder.

A very, very similar question was asked yesterday. (Not quite exact duplicate, but very close.)

Jon Skeet
A: 

-11 < 12, so i 'suppose' they don't actually divide: So -11 = 0x12 -11

Have a try with (0-13) % 12

Aif
+1  A: 

fmod from the math module behaves correctly in python:

>>> from math import *
>>> fmod(-11, 12)
-11.0

-11 is the correct answer..

rejj
"Correct" depends on how you define modulus though. I suspect the JavaScript implementation is correct by their definition too. Follow the link in my answer - the issue isn't as clear as you might expect.
Jon Skeet
A: 

There are two similar operations: modulo and remainder. Modulo represents a more mathematical usage, and remainder more IT usage.

Assume we have two integers, a and b.

MOD(a, b) will return a result which has the same sign as b.

REM(a, b) will return a result which has the same sign as a. - this is what is implemented in C/C++/C# as the % operator and often confusingly called "mod"

You can think of it like this too:

MOD(a, b) will find the largest integer multiple of b (call it "c") that is smaller than a, and return (a - c).

e.g. MOD(-340,60) we find c = -360 is the largest multiple of 60 that is smaller than -340. So we do (-340 - (-360)) = 20.

REM(a, b) will return a value such that (DIV(a,b) * b) + REM(a, b) = a, where DIV() represents integer division.

So for r = REM(-340, 60)

-340 = DIV(-340,60) * 60 + r = -5 * 60 + r = r - 300

This solves to give us r = -40.

A: 

You say MOD(a,b) will return a result with the same sign as b, but then say that it returns (a-c) where c is smaller than a. This second definition means that it always returns a positive number. Which is it?