複數和 cmath 模組

cmath 模組類似於 math 模組,但是為複雜平面定義了適當的函式。

首先,複數是一種數字型別,它是 Python 語言本身的一部分,而不是由庫類提供。因此,對於普通的算術表示式,我們不需要 import cmath

請注意,我們使用 j(或 J)而不是 i

 placeholderCopyz = 1 + 3j

我們必須使用 1j,因為 j 將是變數的名稱而不是數字文字。

 placeholderCopy1j * 1j
Out: (-1+0j)

1j ** 1j
# Out: (0.20787957635076193+0j)     # "i to the i"  ==  math.e ** -(math.pi/2)

我們有 real 部分和 imag(虛構)部分,以及複雜的 conjugate

 placeholderCopy# 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

內建函式 abscomplex 也是語言本身的一部分,不需要任何匯入:

 placeholderCopyabs(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 函式可以帶一個字串,但它不能有空格:

 placeholderCopycomplex('1+1j')
# Out: (1+1j)

complex('1 + 1j')
# Exception: ValueError: complex() arg is a malformed string

但是對於大多數功能我們確實需要模組,例如 sqrt

 placeholderCopyimport cmath

cmath.sqrt(-1)
# Out: 1j

當然,對於複數和實數,sqrt 的行為是不同的。在非複雜的 math 中,負數的平方根會引發異常:

 placeholderCopyimport math

math.sqrt(-1)
# Exception: ValueError: math domain error

提供函式以轉換到極座標和從極座標轉換:

 placeholderCopycmath.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 文件:

 placeholderCopycmath.phase(complex(-1.0, 0.0))
# Out: 3.141592653589793

cmath.phase(complex(-1.0, -0.0))
# Out: -3.141592653589793

cmath 模組還提供許多功能,與 math 模組直接對應。

除了 sqrt 之外,還有複雜版本的 exploglog10,三角函式及其逆(sincostanasinacosatan),以及雙曲函式及其逆函式(sinhcoshtanhasinhacoshatanh)。但請注意,沒有複雜的對應物 math.atan2,兩個引數形式的反正切。

 placeholderCopycmath.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

提供常數 pie。注意這些是 float 而不是 complex

 placeholderCopytype(cmath.pi)
# Out: <class 'float'>

cmath 模組還提供複雜版本的 isinf 和(對於 Python 3.2+)isfinite。請參閱“ Infinity 和 NaN ”。如果複數的實部或其虛部是無窮大,則該複數被認為是無窮大的。

 placeholderCopycmath.isinf(complex(float('inf'), 0.0))
# Out: True

同樣,cmath 模組提供了 isnan 的複雜版本。請參閱“ Infinity 和 NaN ”。如果複數的實部或其虛部是非數字,則該複數被認為是非數字

 placeholderCopycmath.isnan(0.0, float('nan'))
# Out: True

請注意,math.infmath.nan 常量沒有 cmath 對應物(來自 Python 3.5 及更高版本)

Python 3.x >= 3.5

 placeholderCopycmath.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 及更高版本中,cmathmath 模組都有一個 isclose 方法。

Python 3.x >= 3.5

 placeholderCopyz = cmath.rect(*cmath.polar(1+1j))

z
# Out: (1.0000000000000002+1.0000000000000002j)

cmath.isclose(z, 1+1j)
# True