0

before I get into my problem, I want to point out a couple of things: 1)I know there is already an atan2 function in the cmath library, this is purely as an exercise and for my own practice, and 2) I know that the code does not account for 0.

ok, so tan(theta) = y / x, where y and x are coordinates on a plane... that means:

theta = atan(y/x) in Quads I and IV, and theta = atan(y/x) + 180 in Quads II and III

so why when I use the following code:

float atan(float y, float x)
 {
 float result = 0.0f;

if (x > 0) //quads I and IV if x is positive
 { 
result = atanf(y/x);
 }
 else if (x < 0)
 {
 result = atan(y/x) + 180; //quads II and III if x is negative
 }

return result;

 }

does it spit me junk? example, for coordinates (-4,4) it gave me the result of: 179.215, when it should be 135:

atan(4/-4) = -45 degrees + 180 degrees = 135 degrees

but what's happening is it is computing

atan(4.0f/-4.0f) = -0.785398 + 180 degrees = 179.215.

am I missing some step here?

David Torrey
  • 1,335
  • 3
  • 20
  • 43

3 Answers3

11

The standard atan and atan2 functions, as well as all other C functions that work with angles, work with radians, not degrees.

If you want your own function to output degrees, you have to multiply the return value from atanf with 180/pi; to keep everything in radians, add pi instead of 180.

Michael Madsen
  • 54,231
  • 8
  • 72
  • 83
  • I had originally thought it was in radians, but messed up the formula to go rads to degrees, which gave me second guesses. thanks. – David Torrey Jul 14 '12 at 15:02
3

atan speaks in radians, not in degrees...

GL770
  • 2,910
  • 1
  • 14
  • 9
  • nope, (atan(y/x) * 180 / 3.14) + 180. See http://stackoverflow.com/questions/1727881/how-to-use-the-pi-constant-in-c to get the value of pi – GL770 Jul 14 '12 at 15:00
  • yea i had it backwards. thats probably why when i tried it the first time I ruled it out, because I was thinking that it was in radians before – David Torrey Jul 14 '12 at 15:02
3

atan returns a result in radians. You can convert to degrees with degrees=180*radians/π.

arx
  • 16,686
  • 2
  • 44
  • 61