How to find the smallest positive integer comparable to the module m?

I have a variable that has an angle in degrees, which can be either positive or negative. Now I need to make sure that this number is only between 0 and 360. The number is double.

What would be a good algorithm for this? Just making the angle% 360 does not work, because negative numbers ultimately remain negative. The bonus points to the smallest algorithm (aka Code Golf).


EDIT

This seems to be different in different languages. In ActionScript and JavaScript, modulo will return a number between + m and -m:

(-5) % 360 = -5 
+2
source share
3 answers
 d = ((d % 360) + 360) % 360; 

will work if modulo you get a value from -359 to 359.

I personally would put this in a separate function, since it was as ugly as sin.

 def mymodulo(n,m): return ((n % m) + m) % m; 
  • The first modulo gives you a value from -359 to 359.
  • Addition adds to something between 1 and 719.
  • The second module returns this back to the desired range: from 0 to 359.

For code golf, 29 characters, including a new line in Python:

 def f(n,m):return((n%m)+m)%m 

Not that Python really needed this: (-5)%360 gives you 355 in this language :-)

+3
source
 angle - 360 * floor(angle/360) 
+3
source

What language? Modulo should also return positive,

Ruby:

 >> -5 % 360 => 355 

Python:

 >>> -5 % 360 355 

If this does not work in any language, the easiest way is to add or subtract the number that will be on the right side of the module until the solution is between zero and this number inclusive.

0
source

Source: https://habr.com/ru/post/1307944/


All Articles