Python รองรับ Complex Numbers แบบ Built-in ใช้ j แทนหน่วยจินตภาพ (√-1)
การสร้าง Complex Number
>> c = 3 + 6j
>>> type(c)
>>> c1 = complex(3, 6) # complex(real, imag)
>>> c1
(3+6j)
Attributes
>> c = 3 + 6j
>>> c.real # 3.0
>>> c.imag # 6.0
>>> c.conjugate() # 3-6j (conjugate)
คำนวณพื้นฐาน
>> c1 = 3 + 6j
>>> c2 = 6 + 15j
>>> c1 + c2 # (9+21j)
>>> c1 - c2 # (-3-9j)
>>> c1 * c2 # (-72+81j)
>>> c1 / c2 # (0.4138-0.0345j)
# ไม่รองรับ comparison
>>> c1 < c2
TypeError: '<=' not supported between instances of 'complex'
cmath Module: ฟังก์ชันขั้นสูง
import cmath, math, numpy
c = 4 + 4j
# Phase (มุม)
phase = cmath.phase(c) # 0.785 rad
print(numpy.degrees(phase)) # 45.0°
# Polar coordinates
r, phi = cmath.polar(c) # (5.656..., 0.785...)
# Power & Log
print(cmath.exp(c)) # eᶜ
print(cmath.log(c, 2)) # log₂(c)
print(cmath.sqrt(c)) # √c
# Trigonometric
print(cmath.sin(c))
print(cmath.cos(c))
print(cmath.tan(c))
# Hyperbolic
print(cmath.sinh(c))
print(cmath.cosh(c))
print(cmath.tanh(c))
cmath Constants
>> cmath.pi, cmath.e, cmath.tau
(3.14159..., 2.71828..., 6.28318...)
>>> cmath.inf, cmath.infj, cmath.nan, cmath.nanj
(inf, infj, nan, nanj)
การประยุกต์ใช้
- วิศวกรรมไฟฟ้า: Voltage, Current, Impedance
- Signal Processing: FFT, Frequency domain
- Quantum Computing: State vectors
- Geometry & Physics: 2D rotations, oscillations
Python จัดการ Complex Numbers ได้โดยตรง ไม่ต้องสร้างคลาสเอง ทำให้เหมาะกับงานวิทยาศาสตร์/วิศวกรรม