C++ std::atan2
In C++, std::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
std::atan2
- Start with Rise 0, run 1
- Do this Find the direction
- Result 0 radians
#include <iostream>
#include <cmath>
int main() {
std::cout << (std::atan2(0.0, 1.0)) << '\n';
}
0
Syntax
std::atan2(north, east)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonFind 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.
#include <cmath>
#include <cstdio>
int main() {
const double north = 3.0;
const double east = 4.0;
std::printf("%.3f\n", std::atan2(north, east));
return 0;
}
0.644
Walking four blocks east and three north gives an angle of about 0.644 radians above east.
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.
#include <cmath>
#include <cstdio>
int main() {
const double north = 1.0;
const double east = -1.0;
std::printf("%.3f\n", std::atan2(north, east));
return 0;
}
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.
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.