Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Hình học với số phức (Complex Numbers) trong C++

Thư viện <complex> của C++ cho phép biểu diễn điểm trong mặt phẳng 2D bằng số phức, từ đó thực hiện các phép toán hình học một cách ngắn gọn, hiệu quả.

Định nghĩa lớp Point

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

Sau đó dùng point p(4.0, 5.0); và truy cập p.x, p.y.

Ví dụ cơ bản

#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 << ")";
    return 0;
}
The point is :(4, 5)

Ứng dụng hình học

  • Khoảng cách từ gốc: abs(p) (modun số phức).
  • Góc với trục Ox: arg(p) (radian).
  • Quay điểm quanh gốc: p * polar(r, theta).

Ví dụ nâng cao

#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 p) {
    cout << "(" << p.x << ", " << p.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 = my_pt * polar(1.0, PI/2); // quay 90 độ
    cout << "After 90 deg CCW: "; print_point(rot);
    return 0;
}

Kết quả

The point is:(6, 7)
Distance from origin:9.21954
Angle with X-axis: (0.86217) rad = (49.4002)
Point after rotating 90 degrees counter-clockwise, will be: (-6.99972, 6.00032)

Mẹo: Dùng polar(r, theta) tạo số phức dạng cực. Phép nhân số phức tự động thực hiện quay + co giãn.