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

ฟังก์ชัน sqrt() สำหรับจำนวนเชิงซ้อน (Complex Number) ใน C++

บทความนี้สาธิตการใช้งานฟังก์ชัน sqrt() สำหรับจำนวนเชิงซ้อนใน C++ ฟังก์ชันนี้อยู่ในเฮดเดอร์ <complex> ใช้คำนวณรากที่สองของจำนวนเชิงซ้อน

ไวยากรณ์ (Syntax)

template<class T> complex<T> sqrt(const complex<T>& x);

พารามิเตอร์

x – จำนวนเชิงซ้อนที่ต้องการหารากที่สอง

ค่าที่ส่งคืน

ส่งคืนค่าจำนวนเชิงซ้อนที่เป็นรากที่สองของ x

ตัวอย่าง Input/Output

InputOutput
sqrt(3, 8i)(2.4024, 1.6649)
sqrt(7, 1i)(2.6524, 0.1885)

ตัวอย่างโค้ดที่ 1

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

int main() {
    complex<double> x(4, 9);  // 4 + 9i
    cout << "The square root of " << x << " = " << sqrt(x) << endl;
    return 0;
}

ผลลัพธ์

The square root of (4,9) = (2.631,1.710)

ตัวอย่างโค้ดที่ 2

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

int main() {
    complex<double> x(2, 6);  // 2 + 6i
    cout << "The square root of " << x << " = " << sqrt(x) << endl;
    return 0;
}

ผลลัพธ์

The square root of (2,6) = (2.0401,1.4704)

พื้นฐานทางคณิตศาสตร์

สำหรับจำนวนเชิงซ้อน z = x + yi รากที่สองมี 2 ค่า (principal square root คือค่าที่มี real part ≥ 0):

sqrt(z) = ±(√((|z|+x)/2) + i·sign(y)·√((|z|-x)/2))

โดยที่ |z| = √(x² + y²) คือ modulus ของ z

C++ std::sqrt ส่งคืน principal square root (real part ≥ 0 เสมอ)

ตัวอย่างการคำนวณด้วยมือ

หา sqrt(3 + 4i):

|z| = √(3² + 4²) = 5
Real part = √((5+3)/2) = √4 = 2
Imag part = sign(4)·√((5-3)/2) = 1·√1 = 1
sqrt(3+4i) = 2 + 1i  (ตรวจสอบ: (2+i)² = 4 + 4i + i² = 3 + 4i ✓)

ฟังก์ชันที่เกี่ยวข้องใน <complex>

  • sin(), cos(), tan() – ฟังก์ชันตรีโกณมิติ
  • sinh(), cosh(), tanh() – ฟังก์ชันไฮเปอร์บอลิก
  • exp(), log() – เอ็กซ์โพเนนเชียลและลอการิทึม
  • pow() – ยกกำลัง
  • abs(), arg(), norm(), conj(), polar() – ฟังก์ชันอื่นๆ