【Python入門】複素数型(complex型)の使い方

Python入門者向けに複素数型(complex型)の使い方についてまとめました。

## 【はじめに】複素数型とは

Pythonでは、複素数の計算を扱える複素数型(complex型)があります。

# -*- coding: utf-8 -*-
ej = 2 + 3j

print(ej) # (2+3j)
print(type(ej)) # 
複素数型のポイント
1 虚数部はiでなくj
2 jは実部の後に記述
3 虚数部の係数が1の場合は「1j」と記述
4 虚部部が0の場合は「0j」と記述

次のようにcomplex(実部, 虚部)で複素数型を生成することもできます。
変数で係数を指定するときに便利です。

real = 2
imag = 3

c = complex(real, imag)

print(ej) # (2+3j)
print(type(ej)) # 

## 【四則演算】複素数型の計算

他の数値型と同様、四則演算には「+」「-」「*」「/」を用います。

# -*- coding: utf-8 -*-
ej1 = 2 + 3j
ej2 = 3 + 2j

print(ej1 + ej2) # (5+5j)
print(ej1 - ej2) # (-1+1j)
print(ej1 * ej2) # 13j
print(ej1 / ej2) # (0.9230769230769231+0.38461538461538464j)

## 【実部・虚部の係数】real、imag

複素数型の変数から実部・虚部の係数を取り出すこともできます。

# -*- coding: utf-8 -*-
ej = 2 + 3j

print(ej.real) # 2.0
print(ej.imag) # 3.0
詳細記事
1 【Python】複素数型の生成・四則演算

## 【共役複素数】conjugate

conjugate()メソッドを用いて、共役複素数を求めます。

# -*- coding: utf-8 -*-
ej = 2 + 3j

print(ej.conjugate()) # (2-3j)

## 【絶対値】abs()関数

他の数値型と同じく、複素数型もabs関数で絶対値(大きさ)を計算できます。

# -*- coding: utf-8 -*-
ej = 2 + 3j

print(abs(ej)) # 3.605551275463989

## 【位相】math.atan2、cmath.phase

他の数値型と同じく、複素数型もmathモジュールのatan2メソッド、もしくはcmathモジュールのphaseメソッドで位相(偏角)を計算できます。

# -*- coding: utf-8 -*-
import math

ej = 3 + 2j

# 位相(単位rad)を計算
rad = math.atan2(ej.imag, ej.real)

# 単位を度数(degree)に変換
deg = math.degrees(rad)

print(rad) # 0.5880026035475675
print(deg) # 33.690067525979785
# -*- coding: utf-8 -*-
import cmath
import math

ej = 3 + 2j

rad = cmath.phase(ej)

# 単位を度数(degree)に変換
deg = math.degrees(rad)

print(rad) # 0.5880026035475675
print(deg) # 33.690067525979785
詳細記事
1 【Python】複素数の極座標・直交座標の相互変換

## 【極座標変換】cmath.polar

cmath.polar(ej)で極座標(大きさ、位相)を一気に計算できます。

# -*- coding: utf-8 -*-
import cmath
import math

ej = 3 + 2j

abs, rad = cmath.polar(ej)

# 単位を度数(degree)に変換
deg = math.degrees(rad)

print(abs) # 3.605551275463989
print(deg) # 33.690067525979785

## 【直交座標】cmath.rect

極座標(大きさ、位相)から直交座標(実部、虚部)に変換するにはcmath.rectメソッドを使います。

# -*- coding: utf-8 -*-
import cmath
import math

abs = 3.605551275463989    # 大きさ
deg = 33.690067525979785   # 位相(度)
phase = math.radians(deg)  # 位相(ラジン)

# 直交座標に変換
ej = cmath.rect(abs, phase)

print(ej) # (3+1.9999999999999996j)
詳細記事
1 【Python】共役複素数・絶対値・位相の計算
2 Python入門 基本文法
Python
スポンサーリンク
西住工房

コメント