Sunday, January 13, 2019

Python cmath module

The cmath module

Python cmath module provides access to mathematical functions for complex numbers. The functions in this module accept integers, floating-point numbers or complex numbers as arguments. They will also accept any Python object that has either a __complex__() or a __float__()method: these methods are used to convert the object to a complex or floating-point number, respectively, and the function is then applied to the result of the conversion.

A Python complex number z is stored internally using rectangular or Cartesian coordinates. It is completely determined by its real part z.real and its imaginary part z.imag. In other words:

z == z.real + z.imag*1j

A complex number is created from two real numbers. Python complex number can be created using complex() function as well as using direct assignment statement.

Complex numbers are mostly used where we define something using two real numbers. For example, a circuit element that is defined by Voltage (V) and Current (I). They are mostly used in geometry, calculus and scientific calculations.

Polar coordinates give an alternative way to represent a complex number. In polar coordinates, a complex number z is defined by the modulus r and the phase angle phi. The modulus r is the distance from z to the origin, while the phase phi is the counterclockwise angle, measured in radians, from the positive x-axis to the line segment that joins the origin to z.

Python complex numbers are of type complex. Every complex number contains one real part and one imaginary part. Thus a complex number is represented by “ x + yi “. Python converts the real numbers x and y into complex using the function complex(x,y). 
Let’s create a complex number in python, see the code below:

import cmath

c1 = complex(2, 4)
print(type(c1))

print(c1)

The cmath module needs to be import in the python program then using it's complex method we have created a complex number c1. With the help of type() function we can verify that the created number is a complex number. The output of the program is shown below:

<class 'complex'>
(2+4j)

------------------
(program exited with code: 0)


Press any key to continue . . .


The real part can be accessed using the function real() and imaginary part can be represented by imag(). Let's access the real and imaginary part of the complex number created in the previous program:

import cmath

c1 = complex(2, 4)

print ("The real part of complex number is : ",end="") 
print (c1.real) 
  
print ("The imaginary part of complex number is : ",end="") 

print (c1.imag) 

The output of the program is shown below:

The real part of complex number is : 2.0
The imaginary part of complex number is : 4.0

------------------
(program exited with code: 0)


Press any key to continue . . .


Using the conjugate() we can find the complex conjugate, see the code below:

import cmath

c1 = complex(2, 4)

print ("Complex conjugate of complex number "+ str(c1)+ " is : ",end="") 

print (c1.conjugate()) 

The output of the program is shown below:

Complex conjugate of complex number (2+4j) is : (2-4j)

------------------
(program exited with code: 0)


Press any key to continue . . .


Mathematical operations on complex numbers

Complex numbers support mathematical calculations such as addition, subtraction, multiplication and division. The following programs shows these operations:

import cmath

c = 1 + 2j
c1 = 2 + 4j

print ("The Addition of complex numbers is : ",end="") 
print (c + c1) 
  
print ("The Subtraction of complex numbers is : ",end="") 
print (c - c1) 

print ("The Multiplication of complex numbers is : ",end="") 
print (c * c1) 
  
print ("The Division of complex number is : ",end="") 
print (c1 / c)



The output of the program is shown below:

The Addition of complex numbers is : (3+6j)
The Subtraction of complex numbers is : (-1-2j)
The Multiplication of complex numbers is : (-6+8j)
The Division of complex number is : (2+0j)

------------------
(program exited with code: 0)


Press any key to continue . . .

Phase of Complex Number


The phase of a complex number is the angle between the real axis and the vector representing the imaginary part. This is also known as argument of complex number. Phase is returned using phase(), which takes complex number as argument. The range of phase lies from -pi to +pi. i.e from -3.14 to +3.14. The following program determines the phase of our complex number:

import cmath

c1 = 2 + 4j

print ("The phase of complex number is : ",end="") 

print (cmath.phase(c1))

The output of the program is shown below:

The phase of complex number is : 1.1071487177940904

------------------
(program exited with code: 0)


Press any key to continue . . .

The phase returned by math and cmath modules are in radians, we can use numpy.degrees() function to convert it to degrees. NumPy is the fundamental package for scientific computing with Python. See the code below:

import cmath, math, numpy

c = 2 + 2j

# phase
phase = cmath.phase(c)
print('2 + 2j Phase =', phase)

print('Phase in Degrees =', numpy.degrees(phase))

The output of the program is shown below:

2 + 2j Phase = 0.7853981633974483
Phase in Degrees = 45.0

------------------
(program exited with code: 0)


Press any key to continue . . .

Polar and Rectangular Coordinates

We can write a complex number in polar coordinates, which is a tuple of modulus and phase of the complex number. We can use cmath.rect() function to create a complex number in rectangular format by passing modulus and phase as arguments.Conversion to polar is done using polar(), which returns a pair(r,ph) denoting the modulus r and phase angle ph. modulus can be displayed using abs() and phase using phase().

A complex number converts into rectangular coordinates by using rect(r, ph), where r is modulus and ph is phase angle. It returns a value numerically equal to r * (math.cos(ph) + math.sin(ph)*1j).

The following programs shows the conversion from polar to rectangular and vice versa:

import cmath 
import math 

c = 1 + 2j

modulus = abs(c)
phase = cmath.phase(c)
polar = cmath.polar(c)

print('Modulus =', modulus)
print('Phase =', phase)
print('Polar Coordinates =', polar)


print('Rectangular Coordinates =', cmath.rect(modulus, phase))

The output of the program is shown below:

Modulus = 2.23606797749979
Phase = 1.1071487177940904
Polar Coordinates = (2.23606797749979, 1.1071487177940904)
Rectangular Coordinates = (1.0000000000000002+2j)

------------------
(program exited with code: 0)


Press any key to continue . . .

Functions and Constants in cmath module

Functions


1. exp() :- This function returns the exponent of the complex number mentioned in its argument.
2. log(x,b) :- This function returns the logarithmic value of x with the base b, both mentioned in its arguments. If base is not specified, natural log of x is returned.
3. log10() :- This function returns the log base 10 of a complex number.
4. sqrt() :- This computes the square root of a complex number.
5. isfinite() :- Returns true if both real and imaginary part of complex number are finite, else returns false.
6. isinf() :- Returns true if either real or imaginary part of complex number is/are infinite, else returns false.
7. isnan() :- Returns true if either real or imaginary part of complex number is NaN , else returns false.
The following program demonstrates the working of above mentioned functions:
import cmath 
import math 
z = 1 + 2j
x = 1.0
y = 1.0
a = math.inf 
b = math.nan 
# printing exponent of complex number 
print ("The exponent of complex number is : ", end="") 
print (cmath.exp(z))   
# printing log form of complex number 
print ("The log(base 10) of complex number is : ", end="") 
print (cmath.log(z,10)) 
# printing log10 of complex number 
print ("The log10 of complex number is : ", end="") 
print (cmath.log10(z))   
# printing square root form of complex number 
print ("The square root of complex number is : ", end="") 
print (cmath.sqrt(z)) 
# converting x and y into complex number 
z = complex(x,y);    
# converting x and a into complex number 
w = complex(x,a);    
# converting x and b into complex number 
v = complex(x,b);    
# checking if both numbers are finite 
if cmath.isfinite(z): 
       print ("Complex number is finite") 
else : print ("Complex number is infinite")      
# checking if either number is/are infinite 
if cmath.isinf(w): 
       print ("Complex number is infinite") 
else : print ("Complex number is finite") 
# checking if either number is/are infinite 
if cmath.isnan(v): 
       print ("Complex number is NaN") 
else : print ("Complex number is not NaN")
The output of the program is shown below:
The exponent of complex number is : (-1.1312043837568135+2.4717266720048188j)
The log(base 10) of complex number is : (0.3494850021680094+0.480828578784234j)
The log10 of complex number is : (0.3494850021680094+0.480828578784234j)
The square root of complex number is : (1.272019649514069+0.7861513777574233j)
Complex number is finite
Complex number is infinite
Complex number is NaN
------------------
(program exited with code: 0)
Press any key to continue . . .
Constants
The constants in cmath module that are used in the complex number calculations are pi, e, tau, positive infinity, positive complex infinity, NaN and NaN complex. The following program prints the value of these constants:
import cmath
import math 
print('π =', cmath.pi)
print('e =', cmath.e)
print('tau =', cmath.tau)
print('Positive infinity =', cmath.inf)
print('Positive Complex infinity =', cmath.infj)
print('NaN =', cmath.nan)
print('NaN Complex =', cmath.nanj)

The output of the program is shown below:
π = 3.141592653589793
e = 2.718281828459045
tau = 6.283185307179586
Positive infinity = inf
Positive Complex infinity = infj
NaN = nan
NaN Complex = nanj
------------------
(program exited with code: 0)
Press any key to continue . . .
Trigonometric Functions
1. sin() : This function returns the sine of the complex number passed in argument.
2. cos() : This function returns the cosine of the complex number passed in argument.
3. tan() : This function returns the tangent of the complex number passed in argument.
4. asin() : This function returns the arc sine of the complex number passed in argument.
5. acos() : This function returns the arc cosine of the complex number passed in argument.
6. atan() : This function returns the arc tangent of the complex number passed in argument.
The following program demonstrates the working of above mentioned functions:
import cmath 
import math
z = 1 + 2j
# printing sine of the complex number 
print ("The sine value of complex number is : ",end="") 
print (cmath.sin(z))   
# printing cosine of the complex number 
print ("The cosine value of complex number is : ",end="") 
print (cmath.cos(z))   
# printing tangent of the complex number 
print ("The tangent value of complex number is : ",end="") 
print (cmath.tan(z))
# printing arc sine of the complex number 
print ("The arc sine value of complex number is : ",end="") 
print (cmath.asin(z))   
# printing arc cosine of the complex number 
print ("The arc cosine value of complex number is : ",end="") 
print (cmath.acos(z))   
# printing arc tangent of the complex number 
print ("The arc tangent value of complex number is : ",end="") 
print (cmath.atan(z)) 

The output of the program is shown below:
The sine value of complex number is : (3.165778513216168+1.9596010414216056j)
The cosine value of complex number is : (2.032723007019665-3.0518977991517997j)
The tangent value of complex number is : (0.0338128260798967+1.0147936161466335j
)
The arc sine value of complex number is : (0.4270785863924761+1.5285709194809982
j)
The arc cosine value of complex number is : (1.1437177404024204-1.52857091948099
82j)
The arc tangent value of complex number is : (1.3389725222944935+0.4023594781085
2507j)
------------------
(program exited with code: 0)
Press any key to continue . . .
Hyperbolic Functions
1. sinh() : This function returns the hyperbolic sine of the complex number passed in argument.
2. cosh() : This function returns the hyperbolic cosine of the complex number passed in argument.
3. tanh() : This function returns the hyperbolic tangent of the complex number passed in argument.
4. asinh() : This function returns the inverse hyperbolic sine of the complex number passed in argument.
5. acosh() : This function returns the inverse hyperbolic cosine of the complex number passed in argument.
6. atanh() : This function returns the inverse hyperbolic tangent of the complex number passed in argument.
The following program demonstrates the working of above mentioned functions:

import cmath 
import math 

c = 2 + 2j
print('inverse hyperbolic sine =', cmath.asinh(c))
print('inverse hyperbolic cosine =', cmath.acosh(c))
print('inverse hyperbolic tangent =', cmath.atanh(c))

print('hyperbolic sine =', cmath.sinh(c))
print('hyperbolic cosine =', cmath.cosh(c))

print('hyperbolic tangent =', cmath.tanh(c))


The output of the program is shown below:

inverse hyperbolic sine = (1.7343245214879666+0.7542491446980459j)
inverse hyperbolic cosine = (1.7343245214879666+0.8165471820968505j)
inverse hyperbolic tangent = (0.2388778612568591+1.311223269671635j)
hyperbolic sine = (-1.5093064853236156+3.4209548611170133j)
hyperbolic cosine = (-1.5656258353157435+3.2978948363112366j)
hyperbolic tangent = (1.0238355945704727-0.028392952868232294j)

------------------
(program exited with code: 0)


Press any key to continue . . .

Classification Functions


There are some miscellaneous functions to check if the complex number is finite, infinite or nan. There is also a function to check if two complex numbers are close.

The following program demonstrates the working of above mentioned functions:

import cmath 
import math 

print(cmath.isfinite(2 + 2j))  
print(cmath.isfinite(cmath.inf + 2j)) 

print(cmath.isinf(2 + 2j)) 
print(cmath.isinf(cmath.inf + 2j))  
print(cmath.isinf(cmath.nan + 2j))  


print(cmath.isnan(2 + 2j))  
print(cmath.isnan(cmath.inf + 2j))  
print(cmath.isnan(cmath.nan + 2j))  

print(cmath.isclose(2+2j, 2.01+1.9j, rel_tol=0.05))  

print(cmath.isclose(2+2j, 2.01+1.9j, abs_tol=0.005))


The output of the program is shown below:


True
False
False
True
False
False
False
True
True
False

------------------
(program exited with code: 0)

Press any key to continue . . .

The power function


exp(x) :  Return the exponential value e**x. See the following code for it's working:

import cmath 
import math 

c = 2 + 2j
print('e^c =', cmath.exp(c))

The output of the program is shown below:

e^c = (-3.074932320639359+6.71884969742825j)

------------------
(program exited with code: 0)

Press any key to continue . . .

Here I am ending today's discussion. Till we meet next keep practicing and learning Python as Python is easy to learn!

















Share:

0 comments:

Post a Comment