Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

เรขาคณิตด้วย Complex Numbers ใน C++ STL


ใน C++ STL มีคลาส complex (ใน <complex>) ที่สามารถนำมาใช้แทนจุด (Point) ในระนาบ 2 มิติได้ โดยจินตนาการให้ real() คือแกน x และ imag() คือแกน y

การกำหนด Point Class

#include <complex>
typedef complex<double> point;
#define x real()
#define y imag()

หมายเหตุ: x และ y เป็น macro จึงไม่สามารถใช้เป็นชื่อตัวแปรได้

ตัวอย่างพื้นฐาน

#include <iostream>
#include <complex>
using namespace std;

typedef complex<double> point;
#define x real()
#define y imag()

int main() {
    point my_pt(4.0, 5.0);
    cout << "The point is :(" << my_pt.x << ", " << my_pt.y << ")";
}

เอาต์พุท

The point is :(4, 5)

การประยุกต์ทางเรขาคณิต

  • ระยะห่างจากจุดกำเนิด: abs(P)
  • มุมที่ OP ทำกับแกน X: arg(z) (หน่วยเรเดียน)
  • หมุนจุด P รอบจุดกำเนิด: P * polar(r, θ)

ตัวอย่างประยุกต์

#include <iostream>
#include <complex>
#define PI 3.1415
using namespace std;

typedef complex<double> point;
#define x real()
#define y imag()

void print_point(point my_pt) {
    cout << "(" << my_pt.x << ", " << my_pt.y << ")";
}

int main() {
    point my_pt(6.0, 7.0);
    cout << "The point is: "; print_point(my_pt); cout << endl;
    cout << "Distance from origin: " << abs(my_pt) << endl;
    cout << "Angle with X-axis: (" << arg(my_pt) << ") rad = (" << arg(my_pt)*(180/PI) << ") deg" << endl;
    point rot_point = my_pt * polar(1.0, PI/2); // หมุน 90 องศา
    cout << "After 90 deg CCW rotation: "; print_point(rot_point);
}

เอาต์พุท

The point is:(6, 7)
Distance from origin:9.21954
Angle with X-axis: (0.86217) rad = (49.4002) deg
After 90 deg CCW rotation: (-6.99972, 6.00032)

สรุป

การใช้ complex<double> แทน Point ทำให้โค้ดกระชับ อ่านง่าย และใช้ฟังก์ชันคณิตศาสตร์ในตัวได้เลย (abs, arg, polar, conj, norm) เหมาะสำหรับโจทย์เรขาคณิตคำนวณ