Complex numbers

Complex numbers consist of a real part and an imaginary part, which is given the suffix j in Python.

>>> 7 + 2j
(7+2j)

Note

Python expresses the resulting complex number in parentheses to indicate that the output represents the value of a single object:

>>> (5 + 3j) ** (3 + 5j)
(-7.04464115622119-11.276062812695923j)
>>> x = (5 + 3j) * (6 + 8j)
>>> x
(6+58j)
>>> x.real
6.0
>>> x.imag
58.0

Complex numbers consist of a real part and an imaginary part with the suffix j. In the preceding code, the variable x is assigned to a complex number. You can get its „real“ part with the attribute notation x.real and the „imaginary“ part with x.imag.

Advanced functions

The functions in the math module are not applicable to complex numbers; one of the reasons for this is probably that the square root of -1 is supposed to produce an error. Therefore, similar functions for complex numbers have been provided in the cmath module:

cmath.acos(), cmath.acosh(), cmath.asin(), cmath.asinh(), cmath.atan(), cmath.atanh(), cmath.cos(), cmath.cosh(), python3:cmath.e(), cmath.exp(), cmath.log(), cmath.log10(), python3:cmath.pi(), cmath.sin(), cmath.sinh(), cmath.sqrt(), cmath.tan(), cmath.tanh().

To make it clear in the code that these functions are special functions for complex numbers, and to avoid name conflicts with the more normal equivalents, it is recommended to simply import the module to explicitly refer to the cmath package when using the function, for example:

>>> import cmath
>>> cmath.sqrt(-2)
1.4142135623730951j

Warning

Now it becomes clearer why we do not recommend importing all functions of a module with from MODULE import *. If you would import the module math first and then the module cmath, the functions in cmath would have priority over those of math. Also, when understanding the code, it is much more tedious to find out the source of the functions used.

Checks

  • Load the math module and try out some of the functions. Then load the cmath module and do the same.

  • How can you restore the functions of the math module?