I have a variable that holds an angle, in degrees, which can be both positive and negative. I now need to make sure that this number is between 0 and 360 onl开发者_运维百科y. The number is a double.
What would a nice algorithm for doing that be? Simply doing angle % 360 does not work, because negative numbers end up still being negative. Bonus points to the smallest algorithm (aka, Code Golf).
EDIT
Apparently this is different in different languages. In ActionScript and JavaScript, modulo will return a number between +m and -m:
(-5) % 360 = -5
d = ((d % 360) + 360) % 360;
will work if modulo gives you a value between -359 and 359.
I'd personally put this in a separate function since it's as ugly as sin.
def mymodulo(n,m):
return ((n % m) + m) % m;
- The first modulo gives you a value from -359 to 359.
- The addition bumps that up to something between 1 and 719.
- The second modulo brings that back to the range you want, 0 through 359.
For code golf, 29 characters including the newline in Python:
def f(n,m):return((n%m)+m)%m
Not that Python actually needs it: (-5)%360
gives you 355 in that language :-)
angle - 360 * floor(angle/360)
What language? Modulo should also return positive,
Ruby:
>> -5 % 360
=> 355
Python:
>>> -5 % 360
355
If this isn't working in whatever language, the simplest way would be the add or subtract the number that would be on the right side of the modulo until the solution is between zero and that number inclusive.
精彩评论