When taking modulo of negative numbers makes sense?

匿名 (未验证) 提交于 2019-12-03 09:05:37

问题:

I'm curious because we found a bug in our code written 2 years ago. We initialized a 16 bit signed integer with 0x8000 (the platform is of course uses 2's complement representation for negative numbers). In a hardly reproducible special case, modulo by 10 was being performed on this variable to extract individual digits in decimal representation while the value is still 0x8000 (-32768). -32768 % 10 == 248 which makes no sense for our application.

Our platform is OKI 411 micro-controller.

I'm curious, though taking modulo of negative number in this case makes no sense, is there any real life example or practical reason or to get benefit somehow by taking modulo of negative number?

回答1:

I needed to give a more complete answer.

As you say, mathematically makes sense (although, you don't need to be a mathematician to understand that), but let me clarify something. When I said you're interested in the residue, which it's true, one may be mistaken to think that residues for positive (a mod n) or negative (-a mod n) numbers are the same because one would naively drop the sign and carry on the division in the negative case. Of course, you now know this is not correct. You can think of it in this way: When calculating a mod n, first you find out which number n*x (where x is an integer) is closest to a without going over a. After that, you count how many number are there between n*x and a. An example is likely to help here:

Let's suppose you want -282 mod 10, then 10*-29 = -290 is closest to -282 without going over it. And then you simply count how many numbers are in between n*x and a (that is, between 290 and 282). There are 8 numbers, and that's your answer, which is correct. On the hand, for positive numbers (282 mod 10), the closest number to 282 will be 10*28 = 280 (remember, we don't want to go over 282). Therefore, there are 2 numbers in between (also correct).

As for the applications, I'm not sure about one application relying particularly in calculating modulo of negative numbers, but the whole field of Modular arithmetic provides a lot of applications. See the Wikipedia link above to read a bit about them. If it weren't for the mathematical consistency of having modulo operations of negative numbers, probably we would end up with less general theorems, which in turn means, less powerful applications.

With respect to your programming woes:

When either a or n is negative, this naive definition breaks down and programming languages differ in how these values are defined. Although typically performed with a and n both being integers, many computing systems allow other types of numeric operands.

See also this.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!