复数和 cmath 模块
cmath 模块类似于 math 模块,但是为复杂平面定义了适当的函数。
首先,复数是一种数字类型,它是 Python 语言本身的一部分,而不是由库类提供。因此,对于普通的算术表达式,我们不需要 import cmath。
请注意,我们使用 j(或 J)而不是 i。
z = 1 + 3j
我们必须使用 1j,因为 j 将是变量的名称而不是数字文字。
1j * 1j
Out: (-1+0j)
1j ** 1j
# Out: (0.20787957635076193+0j)     # "i to the i"  ==  math.e ** -(math.pi/2)
我们有 real 部分和 imag(虚构)部分,以及复杂的 conjugate:
# real part and imaginary part are both float type
z.real, z.imag
# Out: (1.0, 3.0)
z.conjugate()
# Out: (1-3j)    # z.conjugate() == z.real - z.imag * 1j
内置函数 abs 和 complex 也是语言本身的一部分,不需要任何导入:
abs(1 + 1j)
# Out: 1.4142135623730951     # square root of 2
complex(1)
# Out: (1+0j)
complex(imag=1)
# Out: (1j)
complex(1, 1)
# Out: (1+1j)
complex 函数可以带一个字符串,但它不能有空格:
complex('1+1j')
# Out: (1+1j)
complex('1 + 1j')
# Exception: ValueError: complex() arg is a malformed string
但是对于大多数功能我们确实需要模块,例如 sqrt:
import cmath
cmath.sqrt(-1)
# Out: 1j
当然,对于复数和实数,sqrt 的行为是不同的。在非复杂的 math 中,负数的平方根会引发异常:
import math
math.sqrt(-1)
# Exception: ValueError: math domain error
提供函数以转换到极坐标和从极坐标转换:
cmath.polar(1 + 1j)
# Out: (1.4142135623730951, 0.7853981633974483)    # == (sqrt(1 + 1), atan2(1, 1))
abs(1 + 1j), cmath.phase(1 + 1j)
# Out: (1.4142135623730951, 0.7853981633974483)    # same as previous calculation
cmath.rect(math.sqrt(2), math.atan(1))
# Out: (1.0000000000000002+1.0000000000000002j)
复杂分析的数学领域超出了本例的范围,但是复平面中的许多函数具有分支切割,通常沿着实轴或虚轴。大多数现代平台都支持 IEEE 754 中规定的有符号零,它在分支切割的两侧提供这些功能的连续性。以下示例来自 Python 文档:
cmath.phase(complex(-1.0, 0.0))
# Out: 3.141592653589793
cmath.phase(complex(-1.0, -0.0))
# Out: -3.141592653589793
cmath 模块还提供许多功能,与 math 模块直接对应。
除了 sqrt 之外,还有复杂版本的 exp,log,log10,三角函数及其逆(sin,cos,tan,asin,acos,atan),以及双曲函数及其逆函数(sinh,cosh,tanh,asinh,acosh,atanh)。但请注意,没有复杂的对应物 math.atan2,两个参数形式的反正切。
cmath.log(1+1j)
# Out: (0.34657359027997264+0.7853981633974483j)
cmath.exp(1j * cmath.pi)
# Out: (-1+1.2246467991473532e-16j)   # e to the i pi == -1, within rounding error
提供常数 pi 和 e。注意这些是 float 而不是 complex。
type(cmath.pi)
# Out: <class 'float'>
cmath 模块还提供复杂版本的 isinf 和(对于 Python 3.2+)isfinite。请参阅“ Infinity 和 NaN ”。如果复数的实部或其虚部是无穷大,则该复数被认为是无穷大的。
cmath.isinf(complex(float('inf'), 0.0))
# Out: True
同样,cmath 模块提供了 isnan 的复杂版本。请参阅“ Infinity 和 NaN ”。如果复数的实部或其虚部是非数字,则该复数被认为是非数字。
cmath.isnan(0.0, float('nan'))
# Out: True 
请注意,math.inf 和 math.nan 常量没有 cmath 对应物(来自 Python 3.5 及更高版本)
Python 3.x >= 3.5
cmath.isinf(complex(0.0, math.inf))
# Out: True
cmath.isnan(complex(math.nan, 0.0))
# Out: True
cmath.inf
# Exception: AttributeError: module 'cmath' has no attribute 'inf'
在 Python 3.5 及更高版本中,cmath 和 math 模块都有一个 isclose 方法。
Python 3.x >= 3.5
z = cmath.rect(*cmath.polar(1+1j))
z
# Out: (1.0000000000000002+1.0000000000000002j)
cmath.isclose(z, 1+1j)
# True