math

A module of math functions: square roots, rounding, powers, logarithms, and constants.

On this page

Example

#
Python
import math

print(math.sqrt(144))
print(math.floor(7.8), math.ceil(7.2))
print(math.pi)
print(round(math.pi * 3 ** 2, 2))
print(math.isclose(0.1 + 0.2, 0.3))
Resultsaved result, you can check it
12.0
7 8
3.141592653589793
28.27
True

Definition and usage

#

The math module contains math functions and constants: sqrt() (square root), floor() and ceil() (rounding down and up), pow() (exponentiation), logarithms, trigonometric functions, and the constants pi, e, and inf. You have to import it with import math before use.

floor() and ceil() return integers, and most of the other functions return a float. Trigonometric functions such as sin() and cos() take angles in radians. You convert degrees to radians with radians(), and radians to degrees with degrees().

The module also has functions for integers: gcd() and lcm() (greatest common divisor and least common multiple), factorial(), and comb() (the number of combinations). The isclose() function compares floating-point numbers with a tolerance for tiny rounding errors.

Syntax

#
Syntax
import math

math.sqrt(x)
math.floor(x)
math.ceil(x)
math.isclose(a, b)
math.pi

More examples

#
Number of pages and rounding negative numbers
Python
import math

tasks = 47
per_page = 10
print(math.ceil(tasks / per_page))

print(math.floor(-2.5), int(-2.5))
Resultsaved result, you can check it
5
-3 -2
Divisors, factorials, and combinations
Python
import math

print(math.gcd(24, 36), math.lcm(4, 10))
print(math.factorial(5))
print(math.comb(49, 6))
print(math.hypot(3, 4))
Resultsaved result, you can check it
12 20
120
13983816
5.0

Good practices

#
  • For exponentiation the ** operator is enough, and for absolute value there is the built-in abs(). math.pow() always returns a float.
  • Compare floating-point numbers with math.isclose(), not with ==.
  • The square root of a negative number raises ValueError. For complex numbers, use the cmath module.

Related entries

#

Spotted a mistake or missing an example? Write to us.