Search code examples
javageometrytrigonometrycartesian-coordinates

Calculate angle of point on circumference


I already know how to find a point on the circumference of a circle based on an angle. The code I'm using to do so is below.

x = Math.sin(Math.toRadians(angle)) * radius;
y = Math.cos(Math.toRadians(angle)) * radius;

I'm trying to undo this process.

So far, I have this code, which only works fully for angles less than or equal to 90 degrees.

DecimalFormat df = new DecimalFormat("###.####");

angleFromX = normalize(
    Double.parseDouble(
        df.format(
            Math.toDegrees(
                Math.asin(
                    (x / radius)
                )
            )
        )
    )
);
angleFromY = normalize(
    Double.parseDouble(
        df.format(
            Math.toDegrees(
                Math.acos(
                    (y / radius)
                )
            )
        )
    )
);

And here's normalize method used above.

public static double normalize(double angle) {
    angle %= 360;

    if (angle < 0) {
        angle = angle + 360;
    }

    return angle;
}

Solution

  • You mixed up sin and cos.

    double x = Math.cos(Math.toRadians(angle)) * radius;
    double y = Math.sin(Math.toRadians(angle)) * radius;
    

    To convert back, use this formula:

    double newRadius = Math.hypot(x, y);
    double theta = Math.atan2(y,x);
    double newAngle = Math.toDegrees(theta);
    

    Based on the implementation, you may need to adjust your value of theta (angle).

    • If it's in Quadrant 2 or 3, add 180 degrees.
    • If it's in Quadrant 4, add 360 degrees.

    Also you may need to add:

    newAngle = (newAngle+360)%360
    

    To keep the angle positive and between 0 and 360.