Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Atan2 yields strange result?

Tags:

c#

math

.net-4.0

First, my math is not strong! But I was calculating the angle of a point from the origin (0, 0) to (-1, -1).

This angle is 225° or 5π/4.

  • 5π/4 = 3.9269908169872415480783042290994
  • Math.Atan2(-1, -1) = -2.3561944901923448

Perhaps my understanding of Math.Atan2 is incorrect but I thought it was meant to return the degree of an angle given two points on a circle whose origin is (0, 0). What I assume is happening here is that the result from Atan2 is "flipped" since it is on the negative side of the X axis...can someone confirm and provide the proper way to do this?

This is my test, which fails:

Assert.AreEqual((5 * Math.PI) / 4, Math.Atan2(-1, -1));

And here's my PointD class which holds points X and Y:

public double ToRadians()
{
    double radians = Math.Atan2(this.Y, this.X);

    return radians;
}
like image 373
Josh M. Avatar asked Feb 17 '13 23:02

Josh M.


1 Answers

Your assumption is correct. Atan2 gives a result in the range -pi to +pi.* If you want a number in the range 0 to 2pi, just add 2pi if the result is less than 0.


Note: Asserting for equality on floating-point values like this is usually not a good idea...


* For future reference, this sort of detail is usually given explicitly in the documentation. For example: http://msdn.microsoft.com/en-us/library/system.math.atan2.aspx.

like image 199
Oliver Charlesworth Avatar answered Oct 11 '22 13:10

Oliver Charlesworth