atan2(y, x) คืนค่า อาร์กทันเจนต์ (arctangent) ของ y/x ในช่วง -π ถึง +π ระบุโควดранต์ได้ถูกต้องต่างจาก atan()
Syntax
double atan2(double y, double x);
float atan2(float y, float x);
long double atan2(long double y, long double x);
พารามิเตอร์: y = พิกัด Y, x = พิกัด X
คืนค่า: มุมในเรเดียน (-π ถึง π) - มุมระหว่างแกน X บวกกับจุด (x,y)
ตัวอย่างโค้ดพื้นฐาน
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double y = 10, x = 5;
double ans = atan2(y, x);
cout << "atan2(" << y << "/" << x << ") = " << ans << " radians" << endl;
return 0;
}
ผลลัพธ์
atan2(10/5) = 1.10715 radians
แปลงเป็นองศา (Degrees)
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double y = 10, x = 5;
double ans = atan2(y, x);
double degrees = ans * 180 / M_PI; // ใช้ M_PI จาก cmath
cout << "atan2(" << y << "/" << x << ") = " << degrees << " degrees" << endl;
return 0;
}
ผลลัพธ์
atan2(10/5) = 63.4349 degrees
ตารางโควดранต์และค่า atan2
| โควดранต์ | x | y | ช่วง atan2 (radians) | ช่วง atan2 (degrees) |
|---|---|---|---|---|
| Q1 | + | + | 0 ถึง π/2 | 0° ถึง 90° |
| Q2 | - | + | π/2 ถึง π | 90° ถึง 180° |
| Q3 | - | - | -π ถึง -π/2 | -180° ถึง -90° |
| Q4 | + | - | -π/2 ถึง 0 | -90° ถึง 0° |
กรณีพิเศษ
atan2(0, 0)= 0 (implementation-defined)atan2(+0, -0)= πatan2(-0, -0)= -πatan2(y, 0)= ±π/2 (ขึ้นอยู่กับเครื่องหมาย y)
การประยุกต์ใช้
- คำนวณมุมระหว่าง 2 จุด
- หมุนวัตถุในเกม/กราฟิก
- แปลงพิกัด Cartesian → Polar
- Robotics และการนำทาง
ตัวอย่างประยุกต์: หามุมระหว่าง 2 จุด
double angleBetweenPoints(double x1, double y1, double x2, double y2) {
return atan2(y2 - y1, x2 - x1);
}