Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
complex():複數
語法:
complex(real, imag)
complex(字串)建立一個複數(有實部和虛部的數字)。在數學和工程領域很常用:print(complex(3, 4)) # (3+4j)
print(complex(1, -2)) # (1-2j)
print(complex(5)) # (5+0j)(只有實部)
print(complex()) # 0j
print(complex("3+4j")) # (3+4j)(從字串建立)Python 用 j 表示虛數單位(數學上通常用 i)。也可以直接用字面值建立:
z = 3 + 4j
print(z.real) # 3.0(實部)
print(z.imag) # 4.0(虛部)
print(z.conjugate()) # (3-4j)(共軛複數)複數可以做四則運算:
a = complex(1, 2) # 1+2j
b = complex(3, 4) # 3+4j
print(a + b) # (4+6j)
print(a * b) # (-5+10j)
print(abs(a)) # 2.23...(模:sqrt(1² + 2²))注意:從字串建立時,+ 或 - 前後不能有空格:
# complex("3 + 4j") # ValueError(有空格不行)
complex("3+4j") # OK小小綜合例子
import cmath
# 計算二次方程式的根:x² + 2x + 5 = 0
a, b, c = 1, 2, 5
# 判別式
d = complex(b**2 - 4*a*c)
# 用 cmath.sqrt 可以處理負數
root1 = (-b + cmath.sqrt(b**2 - 4*a*c)) / (2*a)
root2 = (-b - cmath.sqrt(b**2 - 4*a*c)) / (2*a)
print(f"根1:{root1}") # 根1:(-1+2j)
print(f"根2:{root2}") # 根2:(-1-2j)
# 驗證
print(f"驗證根1:{root1**2 + 2*root1 + 5}") # 接近 0