Python, complex型で複素数を扱う(絶対値、偏角、極座標変換など)
Pythonには複素数を扱うためのcomplex
型が標準で用意されている。
単純な計算だけならモジュールをインポートする必要はないが、標準ライブラリcmathをインポートすると複素数に対応した数学関数(指数・対数・三角関数など)も使える。
複素数complexオブジェクトを生成(虚数単位はj)
複素数complex
オブジェクトを生成するには、虚数単位をj
で表し、以下のように記述する。i
ではないので注意。
c = 3 + 4j
print(c)
# (3+4j)
print(type(c))
# <class 'complex'>
虚部が1
の場合、j
と書くとj
という名前の変数とみなされてしまう。1j
と明示的に記述する必要がある。
# c = 3 + j
# NameError: name 'j' is not defined
c = 3 + 1j
print(c)
# (3+1j)
実部が0
の場合は省略してもよい。
c = 3j
print(c)
# 3j
虚部が0
の値を複素数complex
として定義したい場合は0
を明示的に記述する。なお、後述のようにcomplex
と整数int
、浮動小数点数float
との演算も可能。
c = 3 + 0j
print(c)
# (3+0j)
実部・虚部は浮動小数点数float
でも指定できる。指数表記も可能。
c = 1.2e3 + 3j
print(c)
# (1200+3j)
コンストラクタcomplex()
で生成することもできる。complex(実部, 虚部)
と指定する。
c = complex(3, 4)
print(c)
# (3+4j)
複素数の実部・虚部を取得: real, imag属性
複素数complex
の実部と虚部はそれぞれreal
, imag
属性で取得できる。整数値でも浮動小数点数float
となる。
c = 3 + 4j
print(c.real)
print(type(c.real))
# 3.0
# <class 'float'>
print(c.imag)
print(type(c.imag))
# 4.0
# <class 'float'>
real
, imag
属性を変更することはできない。
# c.real = 5.5
# AttributeError: readonly attribute
共役な複素数を取得: conjugate()メソッド
共役な複素数を取得するには、conjugate()
メソッドを使う。
c = 3 + 4j
print(c.conjugate())
# (3-4j)
複素数の絶対値(大きさ)を取得: abs()関数
複素数の絶対値(大きさ)を取得するには、組み込み関数abs()
を使う。
c = 3 + 4j
print(abs(c))
# 5.0
c = 1 + 1j
print(abs(c))
# 1.4142135623730951
複素数の偏角(位相)を取得: cmath.phase()
複素数の偏角(位相)を取得するには、cmath.phase()
を使う。
cmath.phase(x)
はmath.atan2(x.imag, x.real)
と等価。
import cmath
import math
c = 1 + 1j
print(cmath.phase(c))
# 0.7853981633974483
print(cmath.phase(c) == math.atan2(c.imag, c.real))
# True
取得できる角度の単位はラジアン。度に変換したい場合は、math.degrees()
を使う。
print(math.degrees(cmath.phase(c)))
# 45.0
複素数の極座標変換(極形式表現): cmath.polar(), cmath.rect()
複素数の極座標はcmath.polar()
で得られる。
cmath.polar()
は(絶対値, 偏角)
のタプルを返す。(abs(x), cmath.phase(x))
と等価。偏角はラジアン。
import cmath
import math
c = 1 + 1j
print(cmath.polar(c))
# (1.4142135623730951, 0.7853981633974483)
print(cmath.polar(c)[0] == abs(c))
# True
print(cmath.polar(c)[1] == cmath.phase(c))
# True
極座標から直交座標(複素数平面)への変換はcmath.rect()
を使う。cmath.rect(絶対値, 偏角)
と指定すると、対応する複素数complex
が返される。偏角はラジアンで指定する。
print(cmath.rect(1, 0))
# (1+0j)
print(cmath.rect(1, math.pi / 2))
# (6.123233995736766e-17+1j)
絶対値をr
、偏角(位相)をph
とすると、実部はr * math.cos(ph)
、虚部はr * math.sin(ph)
と等価。
r = math.sqrt(2)
ph = math.pi / 4
print(cmath.rect(r, ph))
# (1.0000000000000002+1j)
print(cmath.rect(r, ph).real == r * math.cos(ph))
# True
print(cmath.rect(r, ph).imag == r * math.sin(ph))
# True
複素数の計算(四則演算、べき乗、平方根)
通常の算術演算子を使って、四則演算やべき乗の計算が可能。
c1 = 3 + 4j
c2 = 2 - 1j
print(c1 + c2)
# (5+3j)
print(c1 - c2)
# (1+5j)
print(c1 * c2)
# (10+5j)
print(c1 / c2)
# (0.4+2.2j)
print(c1**3)
# (-117+44j)
複素数complex
と整数int
、浮動小数点数float
との演算もできる。
c = 3 + 4j
print(c + 3)
# (6+4j)
print(c * 0.5)
# (1.5+2j)
平方根は**0.5
でも算出できるが、誤差が生じる。cmath.sqrt()
を使うとより正確な値が算出できる。
import cmath
print((-3 + 4j) ** 0.5)
# (1.0000000000000002+2j)
print((-1) ** 0.5)
# (6.123233995736766e-17+1j)
print(cmath.sqrt(-3 + 4j))
# (1+2j)
print(cmath.sqrt(-1))
# 1j