In the previous chapter, you used operators like +, //, % and ** to work with numbers. But what if you need a square root, the value of pi, a logarithm, or want to round a price to 2 decimal places?
Python has a ready-made toolbox for this called the math module, plus a built-in round() function. In this chapter, we'll learn the most useful math functions, and the different ways Python can round a number, because rounding has a few surprises that even experienced programmers get wrong.
What is the math Module?
The
mathmodule is a part of Python's standard library that provides mathematical functions (likesqrt(),floor(),log()) and constants (likepi).
It comes with Python, so you don't need to install anything. You only need to import it at the top of your program:
import math
print(math.sqrt(16))Output:
4.0The line import math loads the module. After that, you use its functions with a dot: math.function_name(). We'll learn much more about modules and import in the Modules & Packages chapter. For now, just remember to write import math once, at the top.
Useful Constants
The math module stores some famous numbers, so you never have to type them yourself:
import math
print(math.pi)
print(math.e)
print(math.tau)
print(math.inf)
print(math.nan)Output:
3.141592653589793
2.718281828459045
6.283185307179586
inf
nanConstant | Meaning |
|---|---|
| The ratio of a circle's circumference to its diameter (about 3.14159) |
| Euler's number, the base of natural logarithms (about 2.71828) |
| 2 × pi (one full turn of a circle in radians) |
| Positive infinity, larger than every other number |
| "Not a Number", used to represent an undefined result |
Let's use pi to find the area and circumference of a circle:
import math
radius = 7
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
print("Area:", round(area, 2))
print("Circumference:", round(circumference, 2))Output:
Area: 153.94
Circumference: 43.98We used round() here to keep 2 decimal places. Let's understand rounding properly.
Rounding with round()
round() is a built-in function, so it works without importing anything.
round(number) # round to the nearest whole number
round(number, ndigits) # round to ndigits decimal placesRounding to a Whole Number
print(round(3.7))
print(round(3.2))
print(type(round(3.7)))Output:
4
3
<class 'int'>When you don't give ndigits, round() returns an integer.
Rounding to Decimal Places
print(round(3.14159, 2))
print(type(round(3.14159, 2)))Output:
3.14
<class 'float'>With ndigits, the result keeps the type of the input, so a float stays a float.
Negative ndigits: Rounding to Tens, Hundreds, ...
A negative value rounds to the left of the decimal point:
print(round(1234, -2)) # nearest hundred
print(round(1350, -2))Output:
1200
1400The Surprise: Banker's Rounding
At school, we learn that .5 always rounds up. Python does something different. Look at this:
print(round(0.5))
print(round(1.5))
print(round(2.5))
print(round(3.5))
print(round(-2.5))Output:
0
2
2
4
-2When a number is exactly halfway between two values, Python rounds to the nearest even number. This is called round half to even, or banker's rounding.
0.5 -> between 0 and 1 -> 0 is even -> 0
1.5 -> between 1 and 2 -> 2 is even -> 2
2.5 -> between 2 and 3 -> 2 is even -> 2
3.5 -> between 3 and 4 -> 4 is even -> 4Why? If you always round .5 up, then over thousands of values the total drifts upward. Rounding to even sends half of the ties up and half down, so the errors cancel out. This rule only matters for exact ties. round(2.51) is still 3.
The Second Surprise: Floats Aren't Exact
print(round(2.675, 2))Output:
2.67You might expect 2.68. This is not a bug in round(). Computers store floats in binary, and most decimal fractions can't be stored exactly. The number 2.675 is actually stored as something like 2.67499999999999982..., which is slightly below the halfway point, so it rounds down.
You can see the same effect with addition:
print(0.1 + 0.2)Output:
0.30000000000000004Exact "Round Half Up" for Money
If you need the school-style rule (for bills, marks, or money), use the decimal module, which stores decimal numbers exactly:
from decimal import Decimal, ROUND_HALF_UP
price = Decimal("2.675")
rounded = price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(rounded)Output:
2.68Notice that the number is written as a string, "2.675". Writing Decimal(2.675) would copy the inexact float value and bring the problem back. Decimal("0.01") means "keep 2 decimal places".
round() Changes the Value, Not the Display
print(round(62985.6012, 2))Output:
62985.6round() does not add trailing zeros, so you get 62985.6, not 62985.60. To display exactly 2 decimal places, you'll use f-string formatting like f"{value:.2f}", which we'll cover in the f-Strings & String Formatting chapter.
floor(), ceil() and trunc()
Sometimes you don't want the nearest whole number. You want to always go down, always go up, or just chop off the decimal part.
Function | What it does | Think of it as |
|---|---|---|
| Largest integer less than or equal to | Always go down the number line |
| Smallest integer greater than or equal to | Always go up the number line |
| Removes the decimal part | Always go towards zero |
import math
print(math.floor(3.7))
print(math.ceil(3.2))
print(math.trunc(3.7))Output:
3
4
3All three return an int. For positive numbers, floor() and trunc() give the same answer. The difference shows up with negative numbers:
import math
print(math.floor(-3.7))
print(math.ceil(-3.7))
print(math.trunc(-3.7))
print(int(-3.7))Output:
-4
-3
-3
-3Picture the number line:
-4 -3.7 -3 0
----|----------*---------|----------|----
^ ^
floor ceil / trunc / int
(go down) (go up / towards zero)Remember from the Numbers chapter that int() removes the fractional part. So int(x) behaves exactly like math.trunc(x).
All Rounding Methods Side by Side
|
|
|
|
|
|---|---|---|---|---|
3.7 | 4 | 3 | 4 | 3 |
3.2 | 3 | 3 | 4 | 3 |
2.5 | 2 | 2 | 3 | 2 |
-2.5 | -2 | -3 | -2 | -2 |
-3.2 | -3 | -4 | -3 | -3 |
-3.7 | -4 | -4 | -3 | -3 |
Floor Division is Floor, Not Truncation
The // operator you saw in the Numbers chapter rounds the result down (floor), not towards zero:
import math
print(7 // 2)
print(-7 // 2)
print(math.floor(-7 / 2))
print(int(-7 / 2))Output:
3
-4
-4
-3-7 / 2 is -3.5. Floor gives -4, while truncation gives -3. This is a favourite output-prediction question, especially for people coming from C or Java, where integer division truncates towards zero.
Worked Example: How Many Buses?
230 students are going on a trip. Each bus has 50 seats. How many buses are needed?
230 / 50 = 4.6 buses
4 buses are not enough (only 200 seats), so we need 5.
We always round UP -> ceil(4.6) = 5import math
students = 230
seats_per_bus = 50
buses = math.ceil(students / seats_per_bus)
print("Buses needed:", buses)
print("Without math:", -(-students // seats_per_bus))Output:
Buses needed: 5
Without math: 5The second line is a popular trick for ceiling division with integers only: -(-a // b). Floor-dividing the negative number rounds "down" to -5, and the outer minus flips it back to 5. Another common form is (a + b - 1) // b. These tricks stay exact even for very large integers, where converting to a float could lose precision.
The same "round up" idea appears in many problems: pages needed to print n lines, boxes needed to pack n items, or the number of packets needed to send a file.
Powers and Roots
import math
print(math.sqrt(25)) # square root, always a float
print(math.isqrt(26)) # integer square root (rounded down)
print(math.cbrt(27)) # cube root (Python 3.11+)
print(2 ** 0.5) # square root using **Output:
5.0
5
3.0
1.4142135623730951For powers, Python gives you three choices:
import math
print(2 ** 10)
print(pow(2, 10))
print(math.pow(2, 10))
print(pow(2, 10, 1000)) # (2 ** 10) % 1000, computed efficientlyOutput:
1024
1024
1024.0
24Option | Result for integers | Notes |
|---|---|---|
| Exact | The usual choice |
| Exact | Built-in. Also accepts a third argument for modular power: |
| Always a | Can lose precision for big numbers |
Here is why that precision note matters:
import math
print(3 ** 40)
print(int(math.pow(3, 40)))Output:
12157665459056928801
12157665459056928768A float can only hold about 15 to 17 significant digits, so the last digits are wrong. For exact integer answers, use ** or pow().
Checking for a Perfect Square
math.isqrt() works purely with integers, so it's the safest way to check whether a number is a perfect square:
import math
n = 49
root = math.isqrt(n)
print(root * root == n)
n = 50
root = math.isqrt(n)
print(root * root == n)Output:
True
Falsemath.isqrt(50) is 7, and 7 * 7 is 49, not 50. (The == operator checks whether two values are equal. You'll see it properly in the Operators chapter.)
Worked Example: Compound Interest
The formula for compound interest is:
A = P × (1 + r/100) ^ n
P = principal, r = yearly rate in %, n = number of yearsFor P = 50,000, r = 8% and n = 3 years:
A = 50000 × (1.08) ^ 3
= 50000 × 1.259712
= 62985.60
Interest = A - P = 12985.60import math
principal = 50000
rate = 8 # percent per year
years = 3
amount = principal * math.pow(1 + rate / 100, years)
interest = amount - principal
print("Amount:", round(amount, 2))
print("Interest:", round(interest, 2))Output:
Amount: 62985.6
Interest: 12985.6The unrounded value is actually 62985.600000000006, another small float error. That's why we round the final answer.
Absolute Value, Factorial, GCD and LCM
import math
print(abs(-7)) # built-in, keeps the type
print(math.fabs(-7)) # always returns a float
print(math.factorial(5)) # 5 × 4 × 3 × 2 × 1
print(math.gcd(12, 18)) # greatest common divisor
print(math.lcm(4, 6)) # least common multiple (Python 3.9+)
print(math.gcd(24, 36, 60))Output:
7
7.0
120
6
12
12Since Python 3.9, gcd() and lcm() accept any number of arguments. A useful identity for interviews:
lcm(a, b) = (a × b) / gcd(a, b)
lcm(12, 18) = (12 × 18) / 6 = 216 / 6 = 36Combinations and Permutations
Aptitude rounds love these. Python 3.8 added them directly:
import math
print(math.comb(5, 2)) # ways to CHOOSE 2 from 5 (order doesn't matter)
print(math.perm(5, 2)) # ways to ARRANGE 2 from 5 (order matters)Output:
10
20comb(n, r) = n! / (r! × (n - r)!) -> 5! / (2! × 3!) = 120 / 12 = 10
perm(n, r) = n! / (n - r)! -> 5! / 3! = 120 / 6 = 20Logarithms and Exponentials
import math
print(math.log(100)) # natural log (base e)
print(math.log10(1000)) # base 10
print(math.log2(8)) # base 2
print(math.log(8, 2)) # any base: log of 8 to base 2
print(math.exp(2)) # e ** 2Output:
4.605170185988092
3.0
3.0
3.0
7.38905609893065log2() is especially handy in DSA. For example, binary search on 1,024 items needs at most about log2(1024) = 10 halvings.
Prefer log10() and log2() over log(x, base) when you can. They are more accurate:
import math
print(math.log(1000, 10))
print(math.log10(1000))Output:
2.9999999999999996
3.0If you wrote int(math.log(1000, 10)) to count digits, you'd get 2 instead of 3.
Trigonometry: Radians, Not Degrees
The trigonometry functions (sin, cos, tan, and so on) expect angles in radians. Use math.radians() and math.degrees() to convert:
import math
print(math.sin(math.radians(30)))
print(math.cos(0))
print(math.degrees(math.pi))
print(math.radians(180))Output:
0.49999999999999994
1.0
180.0
3.141592653589793The answer for sin(30°) should be 0.5. Again, the tiny difference comes from floating-point storage. A very common mistake is writing math.sin(30), which calculates the sine of 30 radians, a completely different angle.
Distance Between Two Points
import math
x1, y1 = 1, 2
x2, y2 = 4, 6
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print("Distance:", distance)
print("Using hypot():", math.hypot(x2 - x1, y2 - y1))Output:
Distance: 5.0
Using hypot(): 5.0math.hypot(a, b) calculates sqrt(a² + b²) for you. Python 3.8 also added math.dist(p, q), which takes two points directly.
Comparing Floats with math.isclose()
Because floats are not exact, comparing them with == can fail:
import math
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))Output:
False
Truemath.isclose(a, b) returns True when the two numbers are equal up to a tiny tolerance (by default, a relative difference of about 1e-9). Use it whenever you compare results of float calculations.
Quick Reference
Function | Example | Result |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Common Mistakes
1. Forgetting to Import
print(math.sqrt(16))Output (Python 3.12+):
NameError: name 'math' is not defined. Did you forget to import 'math'?Older versions show only the first part of the message. Add import math at the top of the file.
2. Square Root of a Negative Number
import math
print(math.sqrt(-4))Output (Python 3.14):
ValueError: expected a nonnegative input, got -4.0Older Python versions show ValueError: math domain error instead. The same happens with math.log(0) or math.log(-1). The math module only works with real numbers.
3. Expecting round(2.5) to be 3
Python uses banker's rounding, so round(2.5) is 2. If you need "round half up", use Decimal with ROUND_HALF_UP.
4. Using int() When You Meant floor()
For negative numbers, int(-3.7) is -3, but math.floor(-3.7) is -4. Pick the one that matches your problem.
5. Passing Degrees to sin() or cos()
Always convert first: math.sin(math.radians(30)).
6. Comparing Floats with ==
Use math.isclose() instead.
Interview Tips
"What does
round(2.5)return?"2. Python 3 uses round half to even (banker's rounding).round(3.5)is4."Why is
round(2.675, 2)equal to2.67?" Because2.675can't be stored exactly in binary. The stored value is slightly less than 2.675."Difference between
floor(),trunc()andint()?" They agree for positive numbers. For negatives,floor()goes down (-3.7 -> -4), whiletrunc()andint()go towards zero (-3.7 -> -3)."What is
-7 // 2?"-4, because//is floor division."How do you do ceiling division without
math?"-(-a // b)or(a + b - 1) // b."
**vsmath.pow()?"**gives an exactintfor integers.math.pow()always returns afloat.
Summary
Write
import mathonce, then usemath.function().round(x)returns anint;round(x, n)rounds tondecimal places. Exact ties go to the nearest even number.Floats are stored in binary, so small errors like
0.30000000000000004are normal. UseDecimalfor exact money calculations andmath.isclose()for comparisons.floor()always goes down,ceil()always goes up, andtrunc()/int()go towards zero.sqrt(),isqrt(),factorial(),gcd(),lcm(),comb(),perm(),log2()andlog10()cover most placement-style math problems.Trigonometry functions use radians.
Use
round()for the nearest value,ceil()when you must have enough, andfloor()when you can't go over.
In the next chapter, we'll learn how to convert values between types, such as turning the string returned by input() into a number.