Library contents

Java Math.atan2

In Java, Math.atan2 takes a vertical component y and a horizontal component x and returns the signed direction in radians. The signs of both inputs determine the quadrant.

A simple example

Math.atan2

  1. Start with Rise 0, run 1
  2. Do this Find the direction
  3. Result 0 radians
A positive horizontal run with no rise points straight along the positive horizontal axis.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.atan2(0.0, 1.0));
    }
}
Output
0.0

Syntax

Java syntax
Math.atan2(north, east)
JDK 21 method signatures (1)
public static double atan2(double y, double x)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Find a direction on a map

A navigator knows how far a stop lies along two map axes. It needs a direction that distinguishes opposite quadrants even when two routes have the same rise-to-run ratio.

From the programdouble north = 3.0
Result0.644
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        double north = 3.0;
        double east = 4.0;

        System.out.printf(java.util.Locale.ROOT, "%.3f%n", (double) (Math.atan2(north, east)));
    }
}
Output
0.644

Walking four blocks east and three north gives an angle of about 0.644 radians above east.

Advertisements

Choose the correct quadrant for a route

A campus map has routes with similar slopes that point into different quadrants. Use both displacement components to choose the direction so reversing one component changes the reported heading correctly.

From the programdouble north = 1.0
Result2.356
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        double north = 1.0;
        double east = -1.0;

        System.out.printf(java.util.Locale.ROOT, "%.3f%n", (double) (Math.atan2(north, east)));
    }
}
Output
2.356

A step northwest lies at 135 degrees counterclockwise from east, approximately 2.356 radians.

Point a map label up a street

On a square-grid map a stop is 4 blocks east and 2 north of the depot. A designer wants the label to follow the route’s angle above the east axis.

GivenEast 4 · north 2
Worked result0.464 rad

Positive horizontal distance allows either the rise/run form or the two-coordinate form.

What to watch for

Pass the vertical displacement first. A compass bearing measured clockwise from north uses a different convention.

Documentation for Math.atan2