I need to reverse calculation of standard 360 angle to atan2.
It's my standard angle calulation
Standard angle = (int) Math.toDegrees(Math.atan2(y,x));
if(angle < 0)
angle += 360;
I need Math.atan2 value from angle how to achieve that.
I need to reverse calculation of standard 360 angle to atan2.
It's my standard angle calulation
Standard angle = (int) Math.toDegrees(Math.atan2(y,x));
if(angle < 0)
angle += 360;
I need Math.atan2 value from angle how to achieve that.
To translate degrees range 0..360
into radians range -Pi..Pi
:
if(angle > 180)
angle -= 360;
angle_radians = Math.toRadians(angle);
If your angle may be beyond standard range (you did not mentioned this), use integer modulo instead of loops
angle = angle % 360
(check how modulo operator works with negative numbers in your language)
Though your question is not very clear, it seems that you want to retrieve the angle before the statement
if (angle < 0)
angle += 360;
As atan2
returns a value in the range [-π,π)
, i.e. [-180°,180°)
, the subrange [-180°,0°)
is mapped to [180°,360°)
. Then you invert with
if (angle >= 180°)
angle-= 360;
You also need to convert back to radians.
A general solution with O(1) performance:
double generalModulus(double value, double modulus, double offset) {
return value - Math.floor((value-offset)/modulus) * modulus + offset;
}
double normalizeAngleDegrees(double angleInDegrees, double offset) {
return generalModulus(angleInDegrees, 360.0, offset);
}
double normalizeAngleRadians(double angleInRadians, double offset) {
return generalModulus(angleInRadians, 2.0*Math.PI, offset);
}
To use:
double normDeg = normalizeAngleDegrees(angle, -180); // produces angle in range [-180, 180)
double normRad = normalizeAngleRadians(angle, 0); // produces angle in range [0, 2*Pi)
My Own answer
int normalizeAngle(int angle)
{
int newAngle = angle;
while (newAngle <= -180) newAngle += 360;
while (newAngle > 180) newAngle -= 360;
return newAngle;
}