Section 46.1: 高级复数运算
cmath 模块包含使用复数的附加函数。
import cmath
该模块可以计算复数的相位,单位为弧度:
z = 2+3j # A complex number
cmath.phase(z) # 0.982793723247329
它允许在复数的直角坐标表示法和极坐标表示法之间进行转换:
cmath.polar(z) # (3.605551275463989, 0.982793723247329)
cmath.rect(2, cmath.pi/2) # (0+2j)

该模块包含以下函数的复数版本
- 指数函数和对数函数(通常,log 是自然对数,log10 是小数 对数):
cmath.exp(z) # (-7.315110094901103+1.0427436562359045j)
cmath.log(z) # (1.2824746787307684+0.982793723247329j)
cmath.log10(-100) # (2+1.3643763538418412j)
- 平方根
cmath.sqrt(z) # (1.6741492280355401+0.8959774761298381j)
- 三角函数及其反函数:
cmath.sin(z) # (9.15449914691143-4.168906959966565j)
cmath.cos(z) # (-4.189625690968807-9.109227893755337j)
cmath.tan(z) # (-0.003764025641504249+1.00323862735361j)
cmath.asin(z) # (0.5706527843210994+1.9833870299165355j)
cmath.acos(z) # (1.0001435424737972-1.9833870299165355j)
cmath.atan(z) # (1.4099210495965755+0.22907268296853878j)
cmath.sin(z)**2 + cmath.cos(z)**2 # (1+0j)
- 双曲函数及其反函数
cmath.sinh(z) # (-3.59056458998578+0.5309210862485197j)
cmath.cosh(z) # (-3.7245455049153224+0.5118225699873846j)
cmath.tanh(z) # (0.965385879022133-0.009884375038322495j)
cmath.asinh(z) # (0.5706527843210994+1.9833870299165355j)
cmath.acosh(z) # (1.9833870299165355+1.0001435424737972j)
cmath.atanh(z) # (0.14694666622552977+1.3389725222944935j)
cmath.cosh(z)**2 - cmath.sin(z)**2 # (1+0j)
cmath.cosh((0+1j)*z) - cmath.cos(z) # 0j

Section 46.2: 基本复杂算术
Python 内置支持复数运算。虚数单位用 j 表示:
z = 2+3j # A complex number
w = 1-7j # Another complex number
复数可以加、减、乘、除和指数化:
z + w # (3-4j)
z - w # (1+10j)
z * w # (23-11j)
z / w # (-0.38+0.34j)
z**3 # (-46+9j)
Python 还能提取复数的实部和虚部,并计算其绝对值和共轭:
z.real # 2.0
z.imag # 3.0
abs(z) # 3.605551275463989
z.conjugate() # (2-3j)
