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

การใช้งาน Complex Numbers (จำนวน مختلط) ใน Python

Complex number (จำนวน مختلط) เป็นคู่ของจำนวนจริง a และ b เขียนในรูป a + bj (Python ใช้ j แทน i) โดยที่ j² = -1

การสร้าง Complex Number

>> a = 5 + 6j
>>> a
(5+6j)
>>> type(a)

ฟังก์ชัน complex()

>> complex(5)        # real=5, imag=0
(5+0j)
>>> complex(5, 6)   # real=5, imag=6
(5+6j)
>>> complex('3+4j') # จากสตริง
(3+4j)

เข้าถึงส่วน Real และ Imaginary

>> z = 3 + 4j
>>> z.real
3.0
>>> z.imag
4.0
>>> z.conjugate()   # complex conjugate
(3-4j)

การคำนวณทางคณิตศาสตร์

>> z1 = 1 + 2j
>>> z2 = 2 + 3j
>>> z1 + z2
(3+5j)
>>> z1 * z2
(-4+7j)
>>> abs(z1)         # magnitude/modulus
2.23606797749979
>>> import cmath
>>> cmath.phase(z1) # phase/argument (radians)
1.1071487177940904

โมดูล cmath: มีฟังก์ชันคณิตศาสตร์สำหรับ complex numbers (sin, cos, exp, log, sqrt, phase, polar, rect, etc.)