Python Math Functions and the math Module
Math Functions and the math Module
Python offers two levels of mathematical tools:
- Built-in math functions — such as
min(),max(),abs(),pow(),round(), andsum()— which are always available without importing anything. - The
mathmodule — part of Python's standard library — which provides advanced functions and constants such as square roots, rounding up and down, factorials, trigonometry, and π.
Built-in Math Functions
Finding Minimum and Maximum Values
min() and max() return the smallest and largest values from a collection of numbers, or from several separate arguments.
numbers = [12, 45, 7, 89, 23]
lowest = min(numbers)
highest = max(numbers)
print("Minimum value:", lowest)
print("Maximum value:", highest)
Expected output:
Minimum value: 7
Maximum value: 89
They also work with separate values: max(4, 9, 2) returns 9. Calling either function on an empty list raises a ValueError.
Absolute Value
abs() returns the absolute value of a number — its distance from zero. Negative numbers become positive; positive numbers stay the same.
value = -15.8
result = abs(value)
print("Absolute value:", result)
Expected output:
Absolute value: 15.8
Practical use: finding the difference between two values regardless of order, such as abs(actual - expected).
Power Function
pow(x, y) raises x to the power y. It gives the same result as the ** operator.
result = pow(3, 4)
print("Power result:", result)
Expected output:
Power result: 81
3 ** 4 also gives 81. pow() accepts an optional third argument for the remainder after division: pow(2, 10, 1000) returns 24, because 2¹⁰ = 1024 and 1024 % 1000 = 24. This form is used in cryptography and number theory.
Rounding With round()
round() rounds a number to the nearest whole number, or to a given number of decimal places.
print(round(7.6))
print(round(3.14159, 2))
Expected output:
8
3.14
Note: When a value is exactly halfway,
round()rounds to the nearest even number ("banker's rounding"):round(2.5)returns2, andround(3.5)returns4. This reduces bias when rounding large amounts of data.
Adding Values With sum()
prices = [120, 80, 45.5]
print(sum(prices))
Expected output:
245.5
The math Module
For more advanced calculations, import the math module.
Syntax
import math
After importing, use its functions and constants with the math. prefix, such as math.sqrt().
Square Root
math.sqrt() returns the square root of a number.
import math
number = 81
root = math.sqrt(number)
print("Square root:", root)
Expected output:
Square root: 9.0
math.sqrt() always returns a float. Passing a negative number raises ValueError: math domain error. If you need a whole-number square root, math.isqrt(17) returns 4 (the integer part).
Rounding Up and Down: ceil() and floor()
math.ceil()rounds up to the nearest integer (the "ceiling").math.floor()rounds down to the nearest integer (the "floor").
import math
value = 6.7
rounded_up = math.ceil(value)
rounded_down = math.floor(value)
print("Ceil value:", rounded_up)
print("Floor value:", rounded_down)
Expected output:
Ceil value: 7
Floor value: 6
With negative numbers, "up" and "down" refer to the number line:
import math
print(math.ceil(-6.7))
print(math.floor(-6.7))
Expected output:
-6
-7
Comparison of Rounding Approaches
| Value | round() | math.ceil() | math.floor() | int() (truncate) |
|---|---|---|---|---|
| 6.7 | 7 | 7 | 6 | 6 |
| 6.2 | 6 | 7 | 6 | 6 |
| -6.7 | -7 | -6 | -7 | -6 |
Practical example — pages needed: if 47 items are shown 10 per page, the number of pages is math.ceil(47 / 10), which is 5. Rounding down would lose the last page.
The Constant π (Pi)
math.pi provides the value of π (approximately 3.141592653589793), used in geometry and trigonometry.
import math
radius = 5
area = math.pi * radius * radius
print("Area of circle:", area)
print("Rounded area:", round(area, 2))
Expected output:
Area of circle: 78.53981633974483
Rounded area: 78.54
The area of a circle is π × r². Rounding is applied only for display; the full-precision value is kept in area.
The module also provides math.e (Euler's number, approximately 2.718), math.inf (infinity), and math.tau (2π).
Other Useful math Functions
| Function | Description | Example | Result |
|---|---|---|---|
math.factorial(n) | n! (n × (n − 1) × … × 1) | math.factorial(5) | 120 |
math.gcd(a, b) | Greatest common divisor | math.gcd(12, 18) | 6 |
math.trunc(x) | Removes the decimal part | math.trunc(-6.7) | -6 |
math.hypot(x, y) | Length of the hypotenuse, √(x² + y²) | math.hypot(3, 4) | 5.0 |
math.log(x) | Natural logarithm | math.log(math.e) | 1.0 |
math.log10(x) | Base-10 logarithm | math.log10(1000) | 3.0 |
math.sin(x), math.cos(x) | Trigonometric functions (x in radians) | math.cos(0) | 1.0 |
math.radians(d) | Converts degrees to radians | math.radians(180) | 3.141592653589793 |
math.isclose(a, b) | Checks whether two floats are approximately equal | math.isclose(0.1 + 0.2, 0.3) | True |
Practical Example: Distance Between Two Points
import math
x1, y1 = 2, 3
x2, y2 = 8, 11
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print("Distance:", distance)
Expected output:
Distance: 10.0
This applies the distance formula √((x₂ − x₁)² + (y₂ − y₁)²). The same result can be computed more simply with math.hypot(x2 - x1, y2 - y1) or math.dist((x1, y1), (x2, y2)).
Common Mistakes
| Mistake | Problem |
|---|---|
Calling sqrt(81) without the prefix | NameError — use math.sqrt(81) (or from math import sqrt) |
Forgetting import math | NameError: name 'math' is not defined |
math.sqrt() of a negative number | ValueError: math domain error |
Expecting round(2.5) to return 3 | It returns 2 (rounds halves to even) |
Passing degrees to math.sin() | Trigonometric functions expect radians; convert with math.radians() |
Comparing floats with == | Use math.isclose() |
Related Concepts
- Python Numeric Data Types —
int,float, and floating-point precision - Python Operators — arithmetic operators such as
**,//, and% - Python Modules — importing and using standard-library modules