views:

217

answers:

5

Example: I have a circle which is split up into two halfs. One half goes from 0 to -179,99999999999 while the other goes from 0 to 179,99999999999. Typical example: transform.rotation.z of an CALayer. Instead of reaching from 0 to 360 it is slip up like that.

So when I want to develop a gauge for example (in theory), I want to read values from 0 to 360 rather than getting a -142 and thinking about what that might be on that 0-360 scale.

How to convert this mathematically correctly? Sine? Cosine? Is there anything useful for this?

+2  A: 

Isn't the normalization achieved by something as simple as:

assert(value >= -180.0 && value <= +180.0);
if (value < 0)
    value += 360.0;

I'd probably put even this into a function if I'm going to need it in more than one place. If the code needs to deal with numbers that might already be normalized, then you change the assertion. If it needs to deal with numbers outside the range -180..+360, then you have more work to do (adding or subtracting appropriate multiples of 360).

Jonathan Leffler
This approach is more counter-intuitive than negative numbers. Say you rotate between -1 and 1 degrees, the number will jump from 359 to 1. If you put that on a visual display, it will be very annoying. My approach shifts the origin to make the transformation continuous.
ZZ Coder
@ZZ Coder: On a compass, bearing 359° is just 2 degrees removed from 001°, just the same as -1° and +1° are 2 degrees apart. So, I don't understand your objection. However, I still think that adding 180° to a bearing means it points in the opposite direction to where it was pointing before adding an offset.
Jonathan Leffler
A: 

Say x is the value with range (-180, 180), y is the value you want display,

  y = x + 180;

That will change shift reading to range (0, 360).

ZZ Coder
The goal is probably to have the values from -180 through -0 map to 180 to 360, rather than simply to add 180 all values. For directions, adding 180 reverses the direction travelled.
Jonathan Leffler
+2  A: 
while (x < 0)  {
  x = x + 360;
  }

while (x > 360) {
  x = x - 360;
  }

This will work on any value, positve or negative.

Jeanne Pindar
A: 

If you don't mind spending a few extra CPU cycles on values that are already positive, this should work on any value -360 < x < 360:

x = (x + 360) % 360;
Sixten Otto
It depends on the host language, but '%' does not work in C or C++ if the tersm of the expression are not integers.
Jonathan Leffler
Seems I've been spending too much time dabbling in other languages. Looks like there's a function fmod() in math.h, but maybe not on the iPhone. Using a conditional/loop might be safer, then.
Sixten Otto
A: 

I provide code to return 0 - 360 degree angle values from the layer's transform property in this answer to your previous question.

Brad Larson