Search on blog:

Python: Complex number - real and imaginary part

Python has complex numbers which use char j instead of i to define imaginary part.

You can be split complex number to real and imaginary part using .real and .imag

You can use complex() or 1j to convert parts back to complex number.

You can get conjugated number using .conjugate().

You can get modulus (absolute value) using standard abs()

Module cmath has more functions which work with complex numbers.

# complex number

x = -5.79829066331+4.55640490659j

# parts

r = x.real   # float
i = x.imag   # float

# tuple, not complex number

y = (x.real, x.imag)

# complex number again

a = complex(r, i)

b = r + i * 1j

# operations

c = a + b

d = a * b

e = 1j * 1j   # -1

f = abs(x)    # distance - float

g = x.conjugate()

import cmath  # not `math`

h = cmath.sin(x)

print('x:', x, type(x))
print('r:', r, type(r))
print('i:', i, type(i))
print('y:', y, type(y))
print('a:', a, type(a))
print('b:', b, type(b))
print('c:', c, type(c))
print('d:', d, type(d))
print('e:', e, type(e))
print('f:', f, type(f))
print('g:', g, type(g))
print('h:', h, type(h))

Result:

x: (-5.79829066331+4.55640490659j) <class 'complex'>
r: -5.79829066331 <class 'float'>
i: 4.55640490659 <class 'float'>
y: (-5.79829066331, 4.55640490659) <class 'tuple'>
a: (-5.79829066331+4.55640490659j) <class 'complex'>
b: (-5.79829066331+4.55640490659j) <class 'complex'>
c: (-11.59658132662+9.11280981318j) <class 'complex'>
d: (12.8593489434305-52.838720056281346j) <class 'complex'>
e: (-1+0j) <class 'complex'>
f: 7.374347448352657 <class 'float'>
g: (-5.79829066331-4.55640490659j) <class 'complex'>
h: (22.19895896009363+42.126120958884385j) <class 'complex'>

If you like it
Buy a Coffee