Master C
Master C

Reputation: 1546

Convert from Radians to Degrees in Java

I'm trying to get the alpha angle in degrees from x,y when user creates an object.

I wrote the following constructor:

public class Point
{
    private double _radius , _alpha;    

    public Point ( int x , int y )
    {
        _radius = Math.sqrt ( Math.pow(x,2) + Math.pow (y,2) ) ;
        _alpha = ( ( Math.atan (y/x) ) * 180 ) / Math.PI;
    }

}
  1. Am I right that _alpha is now an angle in degrees instead of radians that I got from the atan() method ?

  2. Is there a simple way to do so ?

Thanks !

Upvotes: 36

Views: 94042

Answers (3)

Przemek
Przemek

Reputation: 75

This should be by far the shortest and simplest way:

        _radius = Math.hypot(x, y);
        _alpha = Math.toDegrees(Math.atan2(y, x));

Keep in mind that when computed this way, _alpha will have values between -180 and 180 degrees.

Upvotes: 1

MAK
MAK

Reputation: 26586

The idea looks ok, but I would suggest using Math.atan2 instead of Math.atan.

Upvotes: 5

mP.
mP.

Reputation: 18266

Why not use the built-in method Math.toDegrees(), it comes with the Java SE.

Upvotes: 106

Related Questions