Photo by Erol Ahmed on Unsplash

Python Math Module [Ultimate Guide]

Python’s math module provides you with some of the most popular mathematical functions you may want to use. In this article, I’ll take you through the most common ones. You can also watch the following tutorial video in which I’ll guide you through the article:

The math module is part of the Python standard library, and it is always available with every Python installation. However, you must import it before you can start using the functions it contains.

import math

Now every function in the math library is accessible by calling math.function_name(). If you want to import specific functions, use the standard from math import function_name syntax.

Python Math Floor

The math.floor(x) function takes one argument x – either a float or int – and returns the largest integer less than or equal to x.

>>> math.floor(3.9845794)
3
>>> math.floor(9673.0001)
9673
>>> math.floor(12)
12

The largest numbers less than or equal to 3.9845794 and 9673.0001 are 3 and 9673, respectively. Since 12 is an integer, the result of math.floor(12) is 12 itself.

>>> math.floor(-10.5)
-11

The floor of -10.5 is -11. This can sometimes be confusing but remember that -11 < -10 < -9 < … < -1 < 0.

If you create custom a custom Python class, you can make them work with math.floor() by defining a __floor__() method.

Try It Yourself: Run the following interactive Python shell.

Exercise: Can you figure out the output before running it?

Python Math.Ceil

The math.ceil(x) function takes one argument x – either a float or int – and returns the smallest integer greater than or equal to x.

>>> math.ceil(3.9845794)
4
>>> math.ceil(9673.0001)
9674
>>> math.ceil(12)
12

The smallest numbers greater than or equal to 3.9845794 and 9673.0001 are 4 and 9674, respectively. Since 12 is an integer, the result of math.ceil(12) is 12 itself.

>>> math.ceil(-10.5)
-10

The ceiling of -10.5 is -10. Your instinct that 10 < 10.5 is correct when 10 is a positive number. But the opposite is true for negative numbers, and so -10.5 < -10.

If you create custom a custom Python class, you can make them work with math.ceil() by defining a __ceil__() method.

Python Math Operators

The standard mathematical operators are not defined in the math module but rather in the syntax of Python itself.

To add two numbers together, use the + operator.

>>> 5 + 10
15

To subtract two numbers, use the - operator.

>>> 5 - 10
-5

To multiply two numbers together, use the * operator.

>>> 5 * 10
50

To divide two numbers, use the / operator.

>>> 5 / 10
0.5

Note that this always returns a float even if the result is a whole number.

>>> 10 / 5
2.0

Remember that if you take two random numbers and divide them, it is highly unlikely they will divide each other perfectly, so it is logical that all division with / returns a float.

To raise a number to a certain power, use the ** operator.

>>> 5 ** 10
9765625

This is ‘five to the power of ten‘ and you write it in the same order you would write this out by hand.

Then there are some other operators used less often in mathematics but are incredibly useful for computer science and coding: modulus and floor division.

The modulus operator returns the remainder left when one number is divided by another. You perform this calculation with the % operator in Python.

>>> 13 % 3
1

You should read the above line as ‘13 modulo 3‘, and the result is 1. This is because 3 goes into 13 four times (3 x 4 = 12) and the the total difference between 13 and 12 is: 13 – 12 = 1.

Another way to think of it is if you write 13/3 as a compound fraction, you get 4 + 1/3. Looking at the fraction left over – 1/3 – take the numerator (the top part) to get the final result: 1.

If you do many ‘modulo n’ calculations, the set of possible results ranges from 0 up to and including n-1. So for 3, the range of possible results is 0, 1, and 2.

Here are some more examples:

>>> 14 % 3
2
>>> 15 % 3
0
>>> 16 % 3
1

You can see that 15 % 3 is 0. This result is the case for all multiples of 3.

One incredibly useful way to use the modulo operator is in for loops if you want to do something every n-th iteration.

for i in range(10):
    if i % 4 == 0:
        print('Divisible by 4!!!')
    else:
        print('Not divisible by 4 :(')
Divisible by 4!!!
Not divisible by 4 :(
Not divisible by 4 :(
Not divisible by 4 :(
Divisible by 4!!!
Not divisible by 4 :(
Not divisible by 4 :(
Not divisible by 4 :(
Divisible by 4!!!
Not divisible by 4 :(

Here I used the modulo operator to print Divisible by 4!!! every time i was divisible by 4 – i.e., when i % 4 == 0 – and print Not divisible by 4 :( in all other cases.

The final built-in operator is related to modulo. It performs floor division and is written as //. As the name suggests, floor division is the same as normal division but always rounds the result down to the nearest whole number.

If you write 13/3 as a compound fraction, you get 4 + 1/3. Floor division returns the whole number part of this fraction, 4 in this case.

>>> 13 // 3
4
>>> 13 / 3 
4.333333333333333

Here I calculated ‘thirteen floor three’, and this returns 4. The result of ‘thirteen divided by three’ is 4.3333, and if you round this down, you get 4.

Another way to think of it is if you write 13/3 as a compound fraction, you get 4 + 1/3. Floor division returns the whole number part of this fraction, 4 in this case.

Here are some more examples:

>>> 14 // 3
4
>>> 15 // 3
5
>>> 16 // 3
5

Note that all of the above examples are ints being floor divided by ints. In each case, Python returns an int. But if either of the numbers is a float, Python returns a float.

>>> 14.0 // 3
4.0
>>> 14 // 3.0
4.0

This result is different to normal division / which always returns a float.

You can perform floor division on any two numbers, but you may get surprising results if you add decimal places.

# No difference to normal
>>> 14.999 // 3
4.0
# Returns 3.0, not 4.0!
>>> 14 // 3.999
3.0
# Now we see why
>>> 14 / 3.999
3.500875218804701

When you run 14 // 3.999, the result is 3.0 because 14 / 3.999 is 3.508... and the floor of 3.508... is 3.

Floor division for negative numbers works in the same way.

>>> -14 / 3
-4.666666666666667
>>> -14 // 3
-5

Recall that floor division takes the lower number and that -5 < -4. Thus the result of floor division for negative numbers is not the same as adding a minus sign to the result of floor division for positive numbers.

Try It Yourself: Run the following interactive Python shell.

Exercise: Which line does not produce output integer 42?

Python Math Domain Error

You may encounter a special ValueError when working with Python’s math module.

ValueError: math domain error

Python raises this error when you try to do something that is not mathematically possible or mathematically defined.

import numpy as np
import matplotlib.pyplot as plt

# Plotting y = log(x)
fig, ax = plt.subplots()
ax.set(xlim=(-5, 20), ylim=(-4, 4), title='log(x)', ylabel='y', xlabel='x')
x = np.linspace(-10, 20, num=1000)
y = np.log(x)

plt.plot(x, y)

This is the graph of log(x). Don’t worry if you don’t understand the code, what’s more important is the following point. You can see that log(x) tends to negative infinity as x tends to 0. Thus, it is mathematically meaningless to calculate the log of a negative number. If you try to do so, Python raises a math domain error.

>>> math.log(-10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

Python Math Round

Rounding is more complicated than you might expect. Incorrectly rounding floats has lead to disastrous consequences. The Vancouver Stock Exchange used an overly simplified rounding algorithm when trading stocks. In less than two years, the algorithm resulted in the price of the stock exchange being half of what it should have been!

The round() function is not part of the math module but rather a built-in function you can access at all times.

It accepts two arguments:

round(number[, ndigits])

The number is an int or float, and ndigits is the rounding precision you want after the decimal point. The square brackets around ndigits signify that it is an optional argument. If you omit ndigits, Python rounds number to the closest integer.

# Closest integer
>>> round(10.237)
10
# One decimal place
>>> round(10.237, 1)
10.2
# Two decimal places
>>> round(10.237, 2)
10.24

Here you can see that round() works as you would expect.

First, I want to round 10.237 to an integer. So, let’s look at the first value after the decimal place and round down if it’s less than 5 and up if it’s greater than 5. The first value is 2, and so you round down to get 10. For the next example, round 10.237 to one decimal place. Look at the second decimal place – 3 – and so round it down to get 10.2. Finally, round 10.237 to two decimal places by looking at the third decimal place – 7 – and rounding up to get 10.24.

This algorithm works as expected; however, it is not that simple. Let’s look at rounding 1.5 and 2.5.

>>> round(1.5)
2

This rounds to 2, as expected.

>>> round(2.5)
2

But this also rounds to 2! What is going on?

The round() function applies a type of rounding called ’rounding half to even’. This means that, in the event of a tie, Python rounds to the closest even number.

The mathematical logic underpinning it is explained here, but in short, the reason Python does this is to preserve the mean of the numbers. If all the ties are rounded up (as we are taught in school), then if you round a collection of numbers, the mean of the rounded numbers will be larger than the mean of the actual collection.

Python assumes that about half will be odd for a random collection of numbers, and half will be even. In practice, this is true most of the time. However, there are more mathematically rigorous methods you can use in extreme circumstances.

Note that floating-point arithmetic has some inherent issues that cannot be resolved. Fortunately, this is built into all programming languages, mainly because computers represent floats as binary numbers. Some numbers that have finite floating-point representations – such as 0.1 – have infinite binary representations – 0.0001100110011… – and vice versa. Thus, the round() function is not perfect.

# Expected 2.68 but got 2.67
>>> round(2.675, 2)
2.67

From what I’ve said above, this example should return 2.68 as that is an even number. However, it returns 2.67. This result is not a bug and is a known property of the function. For the vast majority of cases, round() works as I described above, but you should know that it is not perfect. If you want something more precise, use the decimal module.

Python Math Pi

The math module includes some mathematical constants, one of which is π (pi).

>>> math.pi
3.141592653589793

It is the ratio of the circumference of a circle to its diameter and is 3.141592653589793 to 15 decimal places. If you are going to use this constant a lot, I recommend importing it separately to save you typing out math. every time you want to use it.

>>> from math import pi
>>> pi
3.141592653589793

Python Math Sqrt

To calculate the square root of a number, use the math.sqrt(n) function.

>>> math.sqrt(2)
1.4142135623730951
>>> math.sqrt(16)
4.0

Note that this always returns a float. Even if you pass an int and Python can express the result as an int, it always returns a float. This functionality is similar to the division operator and makes logical sense; the vast majority of times you calculate a square root, it will not return an integer.

As of Python 3.8, there is also the function math.isqrt(n) which returns the integer square root for some integer n. This result you get is the same as applying math.sqrt(n) and then math.floor() to the result.

# Only works with Python 3.8
>>> math.isqrt(2)
1
>>> math.isqrt(16)
4

If you pass numbers that have precise square roots, you get a similar result to math.sqrt(), but the result is always an integer.

>>> math.isqrt(16.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

You cannot pass a float.

>>> math.isqrt(17)
4
>>> math.floor(math.sqrt(17))
4

The function math.isqrt(n) is the same as math.floor(math.sqrt(n)) if n is an integer,

Python Math Abs

The abs() function is a built-in function that returns the absolute value of a number. The function accepts integers, floats, and complex numbers as input.

If you pass abs() an integer or float, n, it returns the non-negative value of n and preserves its type. In other words, if you pass an integer, abs() returns an integer, and if you pass a float, it returns a float.

# Int returns int
>>> abs(20)
20
# Float returns float
>>> abs(20.0)
20.0
>>> abs(-20.0)
20.0

The first example returns an int, the second returns a float, and the final example returns a float and demonstrates that abs() always returns a positive number.

Complex numbers are made up of two parts and can be written as a + bj where a and b are either ints or floats. The absolute value of a + bj is defined mathematically as math.sqrt(a**2 + b**2). Thus, the result is always positive and always a float (since taking the square root always returns a float).

>>> abs(3 + 4j)
5.0
>>> math.sqrt(3**2 + 4**2)
5.0

Here you can see that abs() always returns a float and that the result of abs(a + bj) is the same as math.sqrt(a**2 + b**2).

Python Math Random

To generate random numbers, you must use the Python random module rather than the math module. That link takes you to an article I’ve written all about it.

Python Math Degrees

It is important that you can quickly switch between degrees and radians, especially if you work with trigonometric functions.

Let’s say you have an angle r which is in radians, and you want to convert it to degrees. Simply call math.degrees(r).

Let’s look at some common examples.

# You need to use pi a lot, so let's import it
>>> from math import pi
>>> math.degrees(pi)
180.0
>>> math.degrees(pi/4)
45.0
>>> math.degrees(2*pi)
360.0

First, I imported pi so that I could easily use it in all the functions. Then I calculated some common degree-to-radians conversions. Note that math.degrees() always returns a float. This result is expected as the vast majority of the time, the result of a conversion is not a whole number.

Note that, as is always the case with floating-point arithmetic, this function is not perfect.

>>> math.degrees(pi/3)
59.99999999999999

This should return 60.0. But note that since 0.999… recurring equals 1, it will not negatively impact your results.

Python Math Radians

Let’s say you have an angle d in degrees, and you want to convert it to radians. Simply call math.radians(d).

Let’s look at some common examples.

>>> from math import pi
>>> math.radians(180)
3.141592653589793
>>> math.radians(180) == pi
True
>>> math.radians(45)
0.7853981633974483
>>> math.radians(45) == pi/4
True

One downside with converting degrees to radians is that radians are much harder for humans to read. So, I added in the equality statements afterward to show you that 180 degrees, when converted to radians, is π and likewise for 45 degrees and π/4.

This function is especially crucial if you want to use any of the trigonometric functions as they assume you are passing an angle in radians.

Python Math Sin

To calculate the sine of some angle r, call math.sin(r). Note that the function assumes that r is in radians.

>>> math.sin(0)
0
# Assumes angle is in radians!
>>> math.sin(90)
0.8939966636005579
# Convert to radians
>>> math.sin(math.radians(90))
1.0
# Enter as radians
>>> math.sin(pi/2)
1.0

From high school math, we know that sin(90) = 1.0 if 90 is in degrees. But here I demonstrate that you do not get 1.0 if you input 90. Instead, input pi/2, and you get the expected result. Alternatively, you can use the math.radians() function to convert any angle in degrees to radians.

Let’s look at the result for math.sin(pi).

>>> math.sin(pi)
1.2246467991473532e-16

Again, from high school math, you expect the result to be 0.0, but, as is often the case with floating-point arithmetic, this is not the case. Although we know that the sine of 0 and π are the same value, unfortunately, it is not reflected in the output. This result is because π is an infinite decimal that cannot be represented fully in a computer. However, the number is so small that it should not make a massive difference to your calculations. But if you need it to equal 0, there are some methods you can try, but I will not discuss them in this article for brevity.

Finally, note that all the values returned are floats even if Python can represent them as integers.

Python Math Cos

To calculate the cosine of some angle r, call math.cos(r). Note that the function assumes that r is in radians.

>>> math.cos(0)
1.0
# Assumes angle is in radians
>>> math.cos(180)
-0.5984600690578581
# Convert to radians
>>> math.cos(math.radians(180))
-1.0
# Enter angle in radians
>>> math.cos(pi)
-1.0

From high school math, we know that cos(180) = -1.0 if 180 is in degrees. However, the trigonometric functions expect the angle to be in radians. So, you must either convert it to radians using the math.radians(180) function, or enter the actual radians value, which is pi in this case. Both methods give you the answer -1.0 as expected.

Let’s look at the result of math.cos(pi/2).

>>> math.cos(pi/2)
6.123233995736766e-17

The result of math.cos(pi/2) should be 0.0, but instead, it is a tiny number close to 0. This is because π is an infinite decimal that cannot be represented entirely in a computer. This functionality should be fine for most cases. If you must have it equal to 0, check out this Stack Overflow answer for alternative methods you can use.

Python Math Tan

To calculate the tangent of some angle r, call math.tan(r). Note that the function assumes that r is in radians.

>>> math.tan(0)
0.0
>>> math.tan(pi/4)
0.9999999999999999
>>> math.tan(pi/2)
1.633123935319537e+16

The results for math.tan() are similar to those for math.sin() and math.cos(). You get the results you expect for 0.0, but once you start including pi, nothing is exactly what you expect. For example, tan(pi/4) is 1, but Python returns 0.999.... This may not look the same, but, mathematically, they are equal). The result of tan(pi/2) should be positive infinity, but Python returns a huge number instead. This result is nice as it lets you perform calculations with math.tan() without throwing loads of errors all the time.

Conclusion

There you have it; you now know how to use the most common functions in Python’s built-in math module!

You can take the floor or ceiling of any number using math.floor() and math.ceil(). You know all the essential operators, what types they return, and when. You’ve seen that Python raises a Math Domain Error if you try to do something mathematically impossible. And you can use some essential functions and constants for scientific computing such as math.pi, converting angles from degrees to radians and using the most common trigonometric functions – sin, cos, and tan.

There are some more functions I didn’t get the chance to cover in this article, such as the inverse and hyperbolic trigonometric functions. With your knowledge, you’ll easily understand and use them if you quickly read the docs.

Where To Go From Here?

Do you wish you could be a programmer full-time but don’t know how to start?

Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back!

https://tinyurl.com/become-a-python-freelancer

It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.

These are proven, no-BS methods that get you results fast.

This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed.

https://tinyurl.com/become-a-python-freelancer