Monday, February 24, 2020

Complex Numbers In Python

Complex Numbers In Python

The cmath module

The simple arithmetic calculations can be done using the math module in Python, but for complex numbers, we need to use a special module. The cmath module provides all the functionalities to work with the complex numbers. We can use the import command to import the module cmath.

import cmath

a=3+4j

The module cmath can be used to calculate the phase of a complex number, in radians 

cmath.phase(a)

Complex(Imaginary) Number Representation


We can convert the complex numbers from Cartesian(rectangular) into polar representation and vice versa, with the  cmath module, 

cmath.polar(a)

cmath.rect(2,cmath.pi/2)

To calculate the square root,

cmath.sqrt(a)

The exponential and logarithmic functions

The exponential and logarithmic functions are also available in cmath for complex numbers.


cmath.log(a)

cmath.log10(-1000)

cmath.exp(a)

Trigonometric functions and thier inverses

cmath.sin(a)
cmath.cos(a)
cmath.tan(a)
cmath.asin(a)
cmath.acos(a)
cmath.atan(a)

Hyperbolic functions and their inverses


cmath.sinh(a)
cmath.cosh(a)
cmath.tanh(a)
cmath.asinh(a)
cmath.acosh(a)
cmath.atanh(a)

Simple Arithmetic Operations on Imaginary Numbers

Python can also extract the real and imaginary parts of complex numbers, and calculate their absolute value and conjugate
a=3+4j #imaginary number a
b=2+3j #imaginay number b

print ('absolute value of a abs() function',abs(a)) #absolute value
print ('real part of a',a.real) #real part
print ('imaginary part',a.imag) #imaginary part
print ('Conjugate of a ',a.conjugate()) #Conjugate

Arithmatic operations on Complex numebers like addition, substraction multiplication can be done very easily with cmath module
print (''======Arithmatic operations on Complex numbers=========')
print (''a+b= ',a+b)
print ('a-b= ',a-b)
print ('a*b= ',a*b)
print ('a/b= ',a/b)
print ('a**b= ',a**b)
print ('a**2=',a**2)

For Example