Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬 복소수 완벽 가이드: 생성 방법부터 cmath 모듈 활용까지


복소수(complex number)는 실수로부터 만들어지는 숫자입니다. 파이썬에서는 직접 할당문을 이용하거나 complex() 함수를 사용하여 복소수를 손쉽게 생성할 수 있습니다.

복소수는 두 개의 실수가 동시에 필요한 상황에서 주로 활용됩니다. 예를 들어 전압(V)과 전류(C)로 정의되는 전기 회로 계산은 물론, 기하학, 과학적 계산, 미적분학 등 다양한 분야에서 복소수가 사용됩니다.

문법(Syntax)

complex([real[, imag]])

파이썬으로 간단한 복소수 만들기

>>> c = 3 + 6j
>>> print(type(c))
<class 'complex'>
>>> print(c)
(3+6j)
>>>
>>> c1 = complex(3, 6)
>>> print(type(c1))
<class 'complex'>
>>> print(c1)
(3+6j)

위 실행 결과에서 확인할 수 있듯이, 파이썬의 복소수는 complex 타입입니다. 모든 복소수는 하나의 실수부(real part)와 하나의 허수부(imaginary part)로 구성됩니다.

복소수의 속성과 함수

>>> # 복소수
>>> c = (3 + 6j)
>>>
>>> # 실수부 출력
>>> print('복소수의 실수부 = ', c.real)
복소수의 실수부 = 3.0
>>>
>>> # 허수부 출력
>>> print('복소수의 허수부 = ', c.imag)
복소수의 허수부 = 6.0
>>>
>>> # 켤레복소수 출력
>>> print('복소수의 켤레(conjugate) = ', c.conjugate())
복소수의 켤레(conjugate) = (3-6j)

복소수 객체는 .real(실수부), .imag(허수부), .conjugate()(켤레복소수)와 같은 유용한 속성과 메서드를 기본적으로 제공합니다.

복소수의 사칙연산

복소수끼리도 간단한 산술 연산을 수행할 수 있습니다:

>>> # 첫 번째 복소수
>>> c1 = 3 + 6j
>>> # 두 번째 복소수
>>> c2 = 6 + 15j
>>>
>>> # 덧셈
>>> print("두 복소수의 합 =", c1 + c2)
두 복소수의 합 = (9+21j)
>>>
>>> # 뺄셈
>>> print("두 복소수의 차 =", c1 - c2)
두 복소수의 차 = (-3-9j)
>>>
>>> # 곱셈
>>> print("두 복소수의 곱 =", c1 * c2)
두 복소수의 곱 = (-72+81j)
>>>
>>> # 나눗셈
>>> print("두 복소수의 몫 =", c1 / c2)
두 복소수의 몫 = (0.4137931034482759-0.03448275862068964j)

다만, 복소수는 <, >, <=, >= 같은 비교 연산자를 지원하지 않습니다. 비교 연산을 시도하면 TypeError가 발생합니다:

>>> c2 <= c2
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
c2 <= c2
TypeError: '<=' not supported between instances of 'complex' and 'complex'

파이썬 cmath 모듈

파이썬의 cmath 모듈은 복소수 전용 수학 함수들을 제공합니다. 이 모듈을 활용하면 복소수의 위상 계산, 지수·로그 연산, 삼각함수 연산 등을 처리할 수 있습니다.

복소수의 위상(Phase)

복소수의 위상(phase)이란 실수축과 허수부를 나타내는 벡터 사이의 각도를 의미합니다.

mathcmath 모듈이 반환하는 위상 값의 단위는 라디안(radian)이며, numpy.degrees() 함수를 사용하면 이를 도(degree) 단위로 변환할 수 있습니다.

import cmath, math, numpy
c = 4 + 4j
# 위상 계산
phase = cmath.phase(c)
print('4+4j의 위상 =', phase)
print('도(degree) 단위 위상 =', numpy.degrees(phase))
print('-4-4j의 위상 =', cmath.phase(-4-4j), 'radians. Degrees =', numpy.degrees(cmath.phase(-4-4j)))
# math.atan2() 함수로도 위상을 구할 수 있습니다
print('math.atan2()를 이용한 위상 =', math.atan2(2, 1))

실행 결과

4+4j Phase = 0.7853981633974483
Phase in Degrees = 45.0
-4-4j Phase = -2.356194490192345 radians. Degrees = -135.0
Complex number phase using math.atan2() = 1.1071487177940904

cmath 모듈의 상수(Constants)

cmath 모듈에는 복소수 계산에 유용하게 쓰이는 여러 상수들이 포함되어 있습니다:

import cmath
print('π =', cmath.pi)
print('e =', cmath.e)
print('tau =', cmath.tau)
print('양의 무한대 =', cmath.inf)
print('양의 복소 무한대 =', cmath.infj)
print('NaN =', cmath.nan)
print('복소 NaN =', cmath.nanj)

실행 결과

π = 3.141592653589793
e = 2.718281828459045
tau = 6.283185307179586
양의 무한대 = inf
양의 복소 무한대 = infj
NaN = nan
복소 NaN = nanj

거듭제곱과 로그 함수

cmath 모듈은 로그 및 거듭제곱 연산에 유용한 함수들을 제공합니다:

import cmath
c = 1 + 2j
print('e^c =', cmath.exp(c))
print('log2(c) =', cmath.log(c, 2))
print('log10(c) =', cmath.log10(c))
print('sqrt(c) =', cmath.sqrt(c))

실행 결과

e^c = (-1.1312043837568135+2.4717266720048188j)
log2(c) = (1.1609640474436813+1.5972779646881088j)
log10(c) = (0.3494850021680094+0.480828578784234j)
sqrt(c) = (1.272019649514069+0.7861513777574233j)

삼각함수(Trigonometric Functions)

import cmath
c = 2 + 4j
print('역사인(asin) 값:\n ', cmath.asin(c))
print('역코사인(acos) 값:\n', cmath.acos(c))
print('역탄젠트(atan) 값:\n', cmath.atan(c))
print('사인(sin) 값:\n', cmath.sin(c))
print('코사인(cos) 값:\n', cmath.cos(c))
print('탄젠트(tan) 값:\n', cmath.tan(c))

실행 결과

arc sine value:
(0.4538702099631225+2.198573027920936j)
arc cosine value:
(1.1169261168317741-2.198573027920936j)
arc tangent value of complex number c:
(1.4670482135772953+0.20058661813123432j)
sine value:
(24.83130584894638-11.356612711218174j)
cosine value:
(-11.36423470640106-24.814651485634187j)
tangent value:
(-0.0005079806234700387+1.0004385132020523j)

쌍곡선 함수(Hyperbolic Functions)

import cmath
c = 2 + 4j
print('역쌍곡사인(asinh) 값:\n', cmath.asinh(c))
print('역쌍곡코사인(acosh) 값:\n', cmath.acosh(c))
print('역쌍곡탄젠트(atanh) 값:\n', cmath.atanh(c))
print('쌍곡사인(sinh) 값:\n', cmath.sinh(c))
print('쌍곡코사인(cosh) 값:\n', cmath.cosh(c))
print('쌍곡탄젠트(tanh) 값:\n', cmath.tanh(c))

실행 결과

Inverse hyperbolic sine value:
(2.183585216564564+1.096921548830143j)
Inverse hyperbolic cosine value:
(2.198573027920936+1.1169261168317741j)
Inverse hyperbolic tangent value:
(0.09641562020299617+1.3715351039616865j)
Hyperbolic sine value:
(-2.370674169352002-2.8472390868488278j)
Hyperbolic cosine value:
(-2.4591352139173837-2.744817006792154j)
Hyperbolic tangent value:
(1.0046823121902348+0.03642336924740368j)