31
loading...
This website collects cookies to deliver better user experience
cmath
module provides useful functions to handle complex numbers and their properties. The good thing is that the module is already inbuilt and preinstalled in Python. So no need to download and install any third party add-ons! The cmath
module is very similer to math module, but has the functionality to handle complex as well as real numbers. You will find the entire documentation herez= complex(x,y)
>>> import cmath # importing "cmath" for complex number operations
>>> x=2
>>> y=3
>>> z=complex(x,y)
>>> z
(2+3j)
z.real
and z.img
>>> z.real
2.0
>>> z.imag
3.0
import cmath
x = 5
y = 3
# converting x and y into complex number
z = complex(x,y);
print ("The real part of complex number is : ",end="")
print (z.real)
print ("The imaginary part of complex number is : ",end="")
print (z.imag)
The real part of complex number is : 5.0
The imaginary part of complex number is : 3.0
>>> a=complex(2,3)
>>> b=complex(4,5)
>>> a+b
# Adding two complex numbers
(6+8j)
>>> a-b
# Subtracting two complex numbers.
(-2-2j)
>>> a*2
# Multiplying complex number by a scalar
(4+6j)
>>> a*b
# Product of two complex numbers
(-7+22j)
>>> b/4
# Scalar division of complex number
(1+1.25j)
>>> a/b
# Dividing two complex numbers
(0.5609756097560976+0.0487804878048781j)
>>> 1/b
# Reciprocal of a complex number.
(0.09756097560975611-0.12195121951219513j)
>>> a**2
# Squaring a complex number
(-5+12j)
>>> a**b
# Complex number to a complex power
(-0.7530458367485594-0.9864287886477446j)
>>> a//2
# Invalid operation of Dividing and rounding off complex numbers.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't take floor of complex number.
cmath
module and check out the inbuilt functions like phase()
polar()
and many others!