math
A module of math functions: square roots, rounding, powers, logarithms, and constants.
Example
#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))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
#import math
math.sqrt(x)
math.floor(x)
math.ceil(x)
math.isclose(a, b)
math.piMore examples
#import math
tasks = 47
per_page = 10
print(math.ceil(tasks / per_page))
print(math.floor(-2.5), int(-2.5))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))Good practices
#- For exponentiation the
**operator is enough, and for absolute value there is the built-inabs().math.pow()always returns afloat. - Compare floating-point numbers with
math.isclose(), not with==. - The square root of a negative number raises
ValueError. For complex numbers, use thecmathmodule.
Related entries
#- round()Rounds a number to the given number of decimal places.
- abs()Returns the absolute value of a number.
- float()Converts a value to a floating-point number.
- int()Converts a value to an integer.
- randomRandom numbers and items: rolling a die, picking from a list, shuffling, and random samples.
- statisticsBasic statistics without external libraries: mean, median, mode, standard deviation, and quantiles.
Spotted a mistake or missing an example? Write to us.