# Mathematical Modules in Python: Math and Cmath This post is part of a series called Mathematical Modules in Python.
Mathematical Modules in Python: Random

When writing programs in our day-to-day life, we often come across situations where we need to use a little maths to get the task done. Like other programming languages, Python provides various operators to perform basic calculations like * for multiplication, % for modulus, and // for floor division.

If you are writing a program to perform specific tasks like studying periodic motion or simulating electric circuits, you will need to work with trigonometric functions as well as complex numbers. While you can't use these functions directly, you can access them by including two mathematical modules first. These modules are math and cmath.

The first one gives you access to hyperbolic, trigonometric, and logarithmic functions for real numbers, while the latter allows you to work with complex numbers. In this tutorial, I will go over all the important functions offered by these modules. Unless explicitly mentioned, all the values returned are floats.

 Types of Functions Example Functions Rounding Functions floor(), ceil(), fabs() GCD and LCM gcd(), lcm() Trigonometry sin(), cos(), tan() Hyperbolic Functions sinh(), cosh(), tanh() Exponents and Logarithms exp(), log(), pow(), sqrt() Combinatorial Functions factorial(), comb(), perm() Complex Numbers cmath.polar(), cmath.sqrt()

## Rounding Functions

These functions perform various arithmetic operations like calculating the floor, ceiling, or absolute value of a number using the floor(x), ceil(x), and fabs(x) functions respectively. The function ceil(x) will return the smallest integer that is greater than or equal to x. Similarly, floor(x) returns the largest integer less than or equal to x. The fabs(x) function returns the absolute value of x.

Here are a few of the arithmetic functions that Python offers:

## Greatest Common Divisor (GCD) and Least Common Multiple (LCM)

It's easy to calculate the greatest common divisor of two or more numbers in Python using the gcd() function. Similarly, you can use the lcm() function to calculate the least common multiple of an arbitrary number of integers.

What if instead of calculating the GCD or LCM of a list of numbers, you want to calculate their product? The prod() function is helpful for that.

## Trigonometry

These functions relate the angles of a triangle to its sides. They have a lot of applications, including the study of triangles and the modeling of periodic phenomena like sound and light waves. Keep in mind that the angle you provide is in radians.

You can calculate sin(x), cos(x), and tan(x) directly using this module. However, there is no direct formula to calculate cosec(x), sec(x), and cot(x), but their value is equal to the reciprocal of the value returned by sin(x), cos(x), and tan(x) respectively.

Instead of calculating the value of trigonometric functions at a certain angle, you can also do the inverse and calculate the angle at which they have a given value by using asin(x), acos(x), and atan(x).

Are you familiar with the Pythagorean theorem? It states that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides. The hypotenuse is also the largest side of a right-angled triangle. The math module also provides the hypot(a, b) function to calculate the length of the hypotenuse.

## Hyperbolic Functions

Hyperbolic functions are analogs of trigonometric functions that are based on a hyperbola instead of a circle. In trigonometry, the points (cos b, sin b) represent the points of a unit circle. In the case of hyperbolic functions, the points (cosh b, sinh b) represent the points that form the right half of an equilateral hyperbola.

Just like the trigonometric functions, you can calculate the value of sinh(x), cosh(x), and tanh(x) directly. The rest of the values can be calculated using various relations among these three values. There are also other functions like asinh(x), acosh(x), and atanh(x), which can be used to calculate the inverse of the corresponding hyperbolic values.

Since math.pi is equal to about 3.141592653589793, when we used asinh() on the value returned by sinh(math.pi), we got our π back.

## Exponents and Logarithms

You will probably be dealing with powers and logarithms more often than hyperbolic or trigonometric functions. Fortunately, the math module provides a lot of functions to help us calculate logarithms.

You can use log(x,[base]) to calculate the log of a given number x to the given base. If you leave out the optional base argument, the log of x is calculated to the base e. Here, e is a mathematical constant whose value is 2.71828182.... and it can be accessed using math.e. By the way, Python also allows you to access another constant π using math.pi.

If you want to calculate the base-2 or base-10 logarithm values, using log2(x) and log10(x) will return more accurate results than log(x, 2) and log(x, 10). Keep in mind that there is no log3(x) function, so you will have to keep using log(x, 3) for calculating base-3 logarithm values. The same goes for all other bases.

If the value whose logarithm you are calculating is very close to 1, you can use log1p(x). The 1p in log1p signifies 1 plus. Therefore, log1p(x) calculates log(1+x) where x is close to zero. However, the results are more accurate with log1p(x).

You can also calculate the value of a number x raised to the power y by using pow(x, y). Before computing the powers, this function converts both the arguments to type float. If you want the final result to be computed in exact integer powers, you should use the built-in pow() function or the ** operator.

You can also compute the square root of any given number x by using sqrt(x), but the same thing can also be accomplished by using pow(x, 0.5).

## Combinatorial Functions

Combinatorics is an important branch of mathematics which is useful in a variety of fields like algebra, probability, and geometry. We can already use the factorial() function in Python's math module in order to do all our permutation and combination calculations. However, two new functions were added to the module in version 3.9 which allow us to directly calculate permutations and combinations. These are comb(n, k) and perm(n, k). The first, comb(n, k), will calculate the number of ways of choosing k items from a set of n. perm(n, k) will calculate the number of ways k items from a set of n can be arranged. Here are some examples:

One more thing that I would like to mention is that the factorial() function would accept floats with integral values before version 3.9. It still does accept them, but that behavior is now deprecated.

## Complex Numbers

Complex numbers are stored internally using rectangular or Cartesian coordinates. A complex number z will be represented in Cartesian coordinates as z = x + iy, where x represents the real part and y represents the imaginary part. Another way to represent them is by using polar coordinates.

In this case, the complex number z would be defined as a combination of the modulus r and the phase angle phi. The modulus r is the distance between the complex number z and the origin. The angle phi is the counterclockwise angle measured in radians from the positive x-axis to the line segment joining z and the origin.

When dealing with complex numbers, the cmath module can be of great help. The modulus of a complex number can be calculated using the built-in abs() function, and its phase can be calculated using the phase(z) function available in the cmath module. You can convert a complex number in rectangular form to polar form using polar(z), which will return a pair (r, phi), where r is abs(z) and phi is phase(z).

Similarly, you can convert a complex number in polar form to rectangular form using rect(r, phi). The complex number returned by this function is r * (math.cos(phi) + math.sin(phi)*1j).

The cmath module also allows us to use regular mathematical functions with complex numbers. For example, you can calculate the square root of a complex number using sqrt(z) or its cosine using cos(z).

Complex numbers have a lot of applications like modelling electric circuits, fluid dynamics, and signal analysis. If you need to work on any of those things, the cmath module won't disappoint you.

## Final Thoughts

All of these functions we discussed above have their specific applications. For example, you can use the factorial(x) function to solve permutation and combination problems. You can use the trigonometric functions to resolve a vector into Cartesian coordinates. You can also use trigonometric functions to simulate periodic functions like sound and light waves.

Similarly, the curve of a rope hanging between two poles can be determined using a hyperbolic function. Since all these functions are directly available in the math module, it makes it very easy to create little programs that perform all these tasks.

I hope you enjoyed this tutorial. If you have any questions, let me know on the forum.