After you define a complex number, you can use it in any type of mathematical calculation, like this:
>>> result = test * 2
>>> print(result)
(2+6j)
>>>
And as you would expect, you can perform complex number calculations by using other complex
numbers, as in the following example:
>>> test1 = complex(1, 2)
>>> test2 = complex(2, 3)
>>> result = test1 + test2
>>> print(result)
(3+5j)
>>> result2 = test1 * test2
>>> print(result2)
(-4+7j)
>>>
Complex math is not for the faint of heart. If you have to work with complex numbers, though, at least
you have a friend in Python!
Getting Fancy with the math Module
For more advanced math support, you can use the methods found in the Python math module. It
provides some additional mathematical methods commonly found in advanced calculations for
trigonometry, statistics, and number theory.
Fortunately, the Raspbian distribution installs the Python math module by default in the Python
installation, so you don’t have to install it as a separate package. However, you do have to use the
import statement to import the module into your Python script to be able to use the methods:
>>> import math
>>> math.factorial(5)
120
>>>
If there’s just one function you need to use from the math module, but you use it lots of times in your
script, you can import just that function using the from statement:
Click here to view code image
>>> from math import factorial
>>> factorial(7)
5040
>>>
The math module provides lots of mathematical functions for you to use. The following sections
provide a rundown of what it provides.
Number Theory Functions
Number theory functions provide handy features such as absolute values, factorials, and determining
whether a value is a number and, if it is, what type of number. Table 5.2 lists the number theory
functions that you’ll find in the math module.