43

So I thought that negative numbers, when mod'ed should be put into positive space... I cant get this to happen in objective-c

I expect this:

-1 % 3 = 2
 0 % 3 = 0
 1 % 3 = 1
 2 % 3 = 2

But get this

-1 % 3 = -1
 0 % 3 = 0
 1 % 3 = 1
 2 % 3 = 2

Why is this and is there a workaround?

Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
coneybeare
  • 33,113
  • 21
  • 131
  • 183
  • Clojure is the first language I've come across that implements mod correctly. Yay! – Todd Owen Oct 26 '11 at 15:59
  • 2
    @ToddOwen: Python does it properly as well – Claudiu Aug 30 '13 at 16:23
  • @Todd, Lisp has both. – Pacerier Sep 10 '14 at 09:57
  • Use frem(a,b) — the modulo you are expecting (which is the kind used in standard math) is called "remainder" in coding. C has fmod() and frem(), you are using mod (aka "%"), you need to use rem. Modulo in Math === Remainder (rem) in code. Dumb, I know. – Albert Renshaw Jul 07 '16 at 07:36
  • It's been brought to my attention that frem(a,b) was in GNU C only and not carried into Obj-C. The equivalent would be this: `a-b*floor((float)a/(float)b)` – Albert Renshaw Jul 07 '16 at 07:44

12 Answers12

54
result = n % 3;
if( result < 0 ) result += 3;

Don't perform extra mod operations as suggested in the other answers. They are very expensive and unnecessary.

UncleO
  • 8,299
  • 21
  • 29
  • 1
    Doesn't it depend on the processor whether conditionals are better or worse than a modulo? – Nosredna Jun 13 '09 at 05:03
  • 2
    I've never seen a processor where division or modulo isn't the slowest operation. Checking for negative reduces to testing the value of a bit, so is usually one of the fastest instructions. – UncleO Jun 13 '09 at 05:08
  • Yeah. That's probably right. I think in the Core Duo Intels, a division is something like 15-17 cycles. I see a lot of people try to avoid branching nowadays. But with a mod the branch is probably worthwhile. – Nosredna Jun 13 '09 at 05:15
  • It's my understanding that the idea behind avoiding branches is to prevent stalling the pipeline. But performing two mods might stall the pipeline anyway; the second mod operation needs to wait for the result from the first. – UncleO Jun 13 '09 at 05:22
  • 5
    The if() will almost certainly be faster than the second mod; any decent optimizing compiler can turn the if() into a cmov (conditional move) instruction, which will do the same thing without branching. – Adam Rosenfield Jun 13 '09 at 15:12
15

In C and Objective-C, the division and modulus operators perform truncation towards zero. a / b is floor(a / b) if a / b > 0, otherwise it is ceiling(a / b) if a / b < 0. It is always the case that a == (a / b) * b + (a % b), unless of course b is 0. As a consequence, positive % positive == positive, positive % negative == positive, negative % positive == negative, and negative % negative == negative (you can work out the logic for all 4 cases, although it's a little tricky).

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
9

If n has a limited range, then you can get the result you want simply by adding a known constant multiple of 3 that is greater that the absolute value of the minimum.

For example, if n is limited to -1000..2000, then you can use the expression:

result = (n+1002) % 3;

Make sure the maximum plus your constant will not overflow when summed.

Peter N Lewis
  • 17,664
  • 2
  • 43
  • 56
7

We have a problem of language:

math-er-says: i take this number plus that number mod other-number
code-er-hears: I add two numbers and then devide the result by other-number
code-er-says: what about negative numbers?
math-er-says: WHAT? fields mod other-number don't have a concept of negative numbers?
code-er-says: field what? ...
  • the math person in this conversations is talking about doing math in a circular number line. If you subtract off the bottom you wrap around to the top.
  • the code person is talking about an operator that calculates remainder.

In this case you want the mathematician's mod operator and have the remainder function at your disposal. you can convert the remainder operator into the mathematician's mod operator by checking to see if you fell of the bottom each time you do subtraction.

Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284
  • The natural numbers define division such that (n+d)/d==(n/d)+1. The real numbers do too. The real numbers also support -(n/d)==(-n)/d, but the natural numbers do not. It is possible for integers to support one axiom or the other, but not both. While programming language could uphold the first axiom for integers and some do, the creators of FORTRAN decided to support the second instead, and many other languages have followed suit. – supercat Dec 20 '13 at 21:55
5

If this will be the behavior, and you know that it will be, then for m % n = r, just use r = n + r. If you're unsure of what will happen here, use then r = r % n.

Edit: To sum up, use r = ( n + ( m % n ) ) % n

maxwellb
  • 13,366
  • 2
  • 25
  • 35
4

I would have expected a positive number, as well, but I found this, from ISO/IEC 14882:2003 : Programming languages -- C++, 5.6.4 (found in the Wikipedia article on the modulus operation):

The binary % operator yields the remainder from the division of the first expression by the second. .... If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined

e.James
  • 116,942
  • 41
  • 177
  • 214
1

UncleO's answer is probably more robust, but if you want to do it on a single line, and you're certain the negative value will not be more negative than a single iteration of the mod (for example if you're only ever subtracting at most the mod value at any time) you can simplify it to a single expression:

int result = (n + 3) % 3;

Since you're doing the mod anyway, adding 3 to the initial value has no effect unless n is negative (but not less than -3) in which case it causes result to be the expected positive modulus.

devios1
  • 36,899
  • 45
  • 162
  • 260
1

JavaScript does this, too. I've been caught by it a couple times. Think of it as a reflection around zero rather than a continuation.

Nosredna
  • 83,000
  • 15
  • 95
  • 122
1

Why: because that is the way the mod operator is specified in the C-standard (Remember that Objective-C is an extension of C). It confuses most people I know (like me) because it is surprising and you have to remember it.

As to a workaround: I would use uncleo's.

Tobias
  • 6,388
  • 4
  • 39
  • 64
  • Yes, confusing just like you subtract on the y-axis to go up. Just one of those preference things of early on designers of the language. Annoying at first; probably useful later on. In fact I'd bet mod working this way had great utility back when programmers had to design compact functions to get their bytes down in their programs, same reason arrays start at index 0 and not index 1, it made the math more compactable – Albert Renshaw Jul 07 '16 at 07:16
0

Instead of a%b

Use: a-b*floor((float)a/(float)b)

You're expecting remainder and are using modulo. In math they are the same thing, in C they are different. GNU-C has Rem() and Mod(), objective-c only has mod() so you will have to use the code above to simulate rem function (which is the same as mod in the math world, but not in the programming world [for most languages at least])


Also note you could define an easy to use macro for this.

#define rem(a,b) ((int)(a-b*floor((float)a/(float)b)))

Then you could just use rem(-1,3) in your code and it should work fine.

Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
0

Not only java script, almost all the languages shows the wrong answer' what coneybeare said is correct, when we have mode'd we have to get remainder Remainder is nothing but which remains after division and it should be a positive integer....

If you check the number line you can understand that

I also face the same issue in VB and and it made me to forcefully add extra check like if the result is a negative we have to add the divisor to the result

0

There are two choices for the remainder, and the sign depends on the language. ANSI C chooses the sign of the dividend. I would suspect this is why you see Objective-C doing so also. See the wikipedia entry as well.