I am trying to create a simple function that utilizes modular arithmetic. This is essentially a number line that wraps around. Specifically I want to use a Mod 8 number line in Java.
What I want is to compare two numbers between 0 and 7. I want to subtract these numbers to get a difference score. However, instead of 0-7=-7, I want it to equal 1. The idea being that after yo开发者_运维问答u reach 7, the number line wraps around back to 0 (therefore 0 and 7 are only one space across.)
Are there any packages that fit this criterion?
how about ((0-7)+8) % 8
? This should fix up your case.
Note: % is the Modular operator.
It appears you want to reverse what negative numbers do with modulos. Keep in mind that the modulus is the remainder after integer division. Normally you would have a range that looks like this:
-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
You want it to look like this for the same series of values:
1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
If you want to solve for the general case where you can have any negative number (such that it will work for -15, -20, -27 as well as -7) then you have to adjust it after the modulus, like this:
int m = x % 8;
m = (m < 0) ? m + 8 : m;
Essentially this leaves the positive case alone, and will adjust the negative case so the numbers roll over as you want them to.
An alternative way to do this with straight math is to take the modulus twice:
int m = ((x % 8) + 8) % 8
The first modulus gives you your expected range from -7 to 7. The addition adjusts the negative modulus so that it is positive, but of course moves the positive values above 7. The second modulus ensures that all the answers are in the range 0 to 7. This should work for any negative number as well as any positive number.
It sounds like you need to use the % modulo operator. Perhaps write a set of integer functions which work with modulo math, eg. Modulo plus would be =(a+b) % 8;
The modulo operation is what you want. However, the %
operator in Java, which is often called modulo, isn't the mathematical modulo. It's rather the remainder operator. The difference is subtle and often irrelevant. It's only important if you have negative parameters like in your case. I think Wikipedia can explain the exact difference.
For you're "wrap around" you need the mathematical version of modulo which sadly isn't implemented in Java for Integer. However, the BigInteger class has a mod() function which does exactly what you need:
BigInteger.valueOf(0-7).mod(BigInteger.valueOf(8)).longValue()
It's not pretty but works.
Um... there is the built-in modulus operator %
, which is also present in basically every other language that's at all popular these days.
精彩评论