How can I keep the rotation values within a range of 0 to 360° no matter how many times I actually rotated an object? I need this as a value for a driver variable.

For example 945° => 225°.

  • $\begingroup$ Thanks again, var - var // (2 * pi) * 2 * pi and var % (2 * pi both deliver a positive result, which is the positional equivalent to its negative. E.g. -980° => 100° (= -260°). Is there a way to get the precise negative result for negative values directly? I want to keep the sign (+/-) as directional information. $\endgroup$ – Jacquin Aug 6 at 10:42
  • $\begingroup$ I've updated my answer, you probably want fmod $\endgroup$ – rjg Aug 6 at 11:28
  • $\begingroup$ Grumble, nothing like a long comment on answer being deleted as you type. Mapping to (0, 2pi) expects a positive result. Keeping the sign would require mapping to (-2pi, 2pi) something like var % ((-2 if var < 0 else 2) * pi) There will be a big switch in value at the boundary. $\endgroup$ – batFINGER Aug 6 at 11:43

Modulo's partner in crime.

Alternatively to modulus could use its partner in crime div. a // (2 * pi) is how many integer multiples of 2pi the value is, eg if a = -3 * pi / 2 we get -1. If we subtract -1 multiples of 2pi from a we get pi / 2.

a - a // (2 * pi) * 2 * pi

You can use modulo x % 360.0, or x % (2 * pi) when operating in radians, which will wrap around to zero when the value x reaches a multiple of 360.0 or 2𝜋.

If you want signed results you can use fmod(x, 2*pi).

Beware of floating point inaccuracies when using the % operator.

  • $\begingroup$ Thanks, I tried it as a scripted expression var%(2*pi) if var > 0 else var%(2*-pi) (var = rotation value in radians), which does what I want both for positive and negative rotation values. But the negative ones are not precisely calculated, so I get for -360° not 0° but -0.00001°? Is there a way to fix this? $\endgroup$ – Jacquin Aug 6 at 0:27
  • 1
    $\begingroup$ Equivalent of fabs(var % (2 * pi)) $\endgroup$ – batFINGER Aug 6 at 1:19
  • $\begingroup$ In hindsight the fabs is unnecessary For some reason abs isn't in the driver namespace. . @Jacquin When using modulo the result a % b is always sign of b. This explains the sign. Hence simply use var % (2 * pi) Please accept this answer. $\endgroup$ – batFINGER Aug 6 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.