Assumptions are the mother of all.
While working on one of my side projects at work, I encounted something interesting with the % sign. The code that I'm going to talk about has nothing to do with any upcoming products -- it's simply a side project I'm working on in my free time that uses WCF and WPF (which are 2 major features of the .NET Framework 3.0). That being said, I've (hopefully) abstracted away everything project specific.
The problem I encountered came from doing some basic math in C# code. Simply, I construct an equation and evaluate what the answer should be by going from left to right (ignoring operator precedence). So when I came up with some final result, I wanted to double check that I was correct. But since I don't keep track of every equation or answer, I had to write a quick tool to trace through it. I'm a big fan of Python for prototyping because I've spent a lot of time in it and understand it well. So I copied over my C# code, made some slight modifications to save the intermediate data and then parse and print the data at the end, and ran it.
My final answer in Python didn't match that from the one calculated in C# (note that C++ returns the same as C#). The algorithm looked correct, but the final results didn't match.
Eventually, I found my problem. Take the following simple equation as an example:
-13 % 6 = ?
C# evaluates this to -1. Python, on the other hand, evaluates to 5. Um...what? Which one is correct?
Well, it depends on your point of view. Technically they're both correct. Just one method takes it one step further than the other.
-13 + 6 = -7
-7 + 6 = -1 (C# answer)
-1 + 6 = 5 (Python answer)
Hm. At first I thought that the in Python the answer will always be in the set {0, 1, 2, .... n-1 }, and the C# answer will always be in the set {0, ±1, ±2, .... ±(n-1) }. To check this, I ran another simple equation through Python and C#.
8 % -3 = ?
8 + -3 = 5
5 + -3 = 2 (C# answer)
2 + -3 = -1 (Python answer)
Theory crushed. Python and C# follow the same basic principle rule of all the answer being in the set {0, ±1, ±2, ... ±(n-1) }. But why does Python always take it further than the C# ?
So I looked up the community definition of modulo.
It turns out that the % sign has no strict definition. Python keeps the same sign as the divisor. C# keeps the same sign as the dividend.
What you should take away : don't always assume that operators will work the same in different languages.
Extra credit :
Windows Live Search and Google both provide basic calculator functions in their search. For example, searching for the term "2 + 2" in WLS and Google both give 4. But what about "-13 % 6"? Why do / don't they give the same answer?
Answer