Python Math Functions: Rounding, Factorials, and Distance
Introduction
Python math functions help translate a requirement into a calculation. A warehouse needs enough boxes for an order, a sensor report needs to discard a fractional change, and a route calculation needs the distance between two points. The correct function depends on the rounding direction, argument type, and expected result.
This PCAP-31-03 lesson covers objective 1.2 in Modules and Packages (12% of the score, 6 of 40 items). You will compare ceil, floor, and trunc, then apply sqrt, factorial, and hypot to worked examples.
Learning objectives
After this lesson you can:
- Use
ceil(),floor()andtrunc()and explain the difference for negative numbers. - Use
sqrt()andfactorial()and name the exceptions raised for invalid arguments. - Use
hypot()to compute a distance and relate it to the Pythagorean theorem. - Distinguish the return types of the
mathfunctions from the built-inround(). - Explain how
round()treats halves and why it is not the same asmath.floor()ormath.ceil(). - Choose the right function for a business requirement (round up, round down, cut off).
Getting started with math
The math module is part of Python’s standard library. Review Python imports and namespaces if you need to check which names the following statements bind:
import math
from math import ceil, floor, trunc, factorial, hypot, sqrtUsing import math and the prefix math. keeps the origin visible, which is why most code in this course uses it. The module also supplies the constants math.pi and math.e:
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045Three ways to turn a float into an integer
The three functions ceil, floor and trunc all convert a floating-point number to an integer, but they choose different neighbours.
math.ceil(x): the smallest integer greater than or equal tox(rounds toward positive infinity).math.floor(x): the largest integer less than or equal tox(rounds toward negative infinity).math.trunc(x): removes the fractional part (rounds toward zero).
For positive numbers, floor and trunc give the same result. For negative numbers they do not:
| x | ceil(x) |
floor(x) |
trunc(x) |
int(x) |
round(x) |
|---|---|---|---|---|---|
| 2.3 | 3 | 2 | 2 | 2 | 2 |
| 2.7 | 3 | 2 | 2 | 2 | 3 |
| 2.0 | 2 | 2 | 2 | 2 | 2 |
| -2.3 | -2 | -3 | -2 | -2 | -2 |
| -2.7 | -2 | -3 | -2 | -2 | -3 |
Study the last two rows. For -2.3, the integer just above is -2 (ceil) and the integer just below is -3 (floor). trunc simply drops .3 and gives -2. This negative-number behaviour is the single most common point of confusion.
import math
print(math.ceil(-2.3)) # -2
print(math.floor(-2.3)) # -3
print(math.trunc(-2.3)) # -2Three details are often tested:
- For an integral float such as
2.0, each returns the equal integer2. The numeric value is the same and the type changes. - All three return an
int, not a float:math.ceil(2.1)is3, not3.0. math.trunc(x)behaves likeint(x)for floats. They are not exactly the same function (trunccalls the object's__trunc__method), but for ordinary numbers you can treat them alike.
Worked example: parcels for an order
Problem. A shop ships items in boxes that hold 40 items each. An order has 2 450 items. How many boxes are needed, and which expression is correct?
Step 1: compute the exact ratio. 2450 / 40 = 61.25. You cannot ship a quarter of a box.
Step 2: decide the rounding direction. The boxes must hold all the items, so the number must never be less than 61.25. The correct operation is "round up", which is ceil.
Step 3: write and run.
import math
items = 2450
box_size = 40
boxes = math.ceil(items / box_size)
print(boxes) # 62Solution: 62 boxes. The last box has 10 items (61 full boxes hold 2 440 items).
Why the other choices are worse.
math.floor(61.25)gives 61: ten items would be left behind.round(61.25)gives 61 as well, andround(61.5)would give 62 for the wrong reason. Rounding to the nearest integer says nothing about capacity.math.trunc(61.25)gives 61, identical tofloorhere.- A hand-made alternative that avoids
mathexists:-(-2450 // 40)also gives 62, because floor division rounds toward negative infinity. It works but hides the intent;math.ceilstates it directly.
If the order has an exact multiple, say 2 400 items, math.ceil(2400 / 40) returns 60: no extra box, because ceil of a whole number is that number.
sqrt() and factorial()
Square roots
math.sqrt(x) returns the square root as a float, always, even for perfect squares.
import math
print(math.sqrt(144)) # 12.0
print(math.sqrt(2)) # 1.4142135623730951For a negative argument the real square root does not exist, so Python raises a ValueError:
math.sqrt(-1) # ValueError: math domain errorFor this call, the exception is ValueError. Other invalid math calls can raise a different exception, such as TypeError for an unsupported argument type or OverflowError for an overflowing result. (If you really need complex roots, the cmath module, which appeared in lesson 1, supplies them.)
Factorial
math.factorial(n) returns n!, the product of all whole numbers from 1 to n, as an int.
import math
print(math.factorial(5)) # 120
print(math.factorial(0)) # 1By definition 0! = 1, so factorial(0) is 1. The integer result is exact. Computing very large factorials is limited by available time and memory.
Invalid arguments raise exceptions of different types:
| Call | Result | Reason |
|---|---|---|
math.factorial(-1) |
ValueError |
factorial is not defined for negative values |
math.factorial(3.5) |
TypeError |
the argument must be an integer |
math.factorial(3.0) |
TypeError since Python 3.10 |
floats are not accepted, even whole ones |
Remember the pairing: a wrong value (outside the domain) gives ValueError; a wrong type gives TypeError. The syllabus-level facts are the integer result and the behaviour for 0; the float case is a good illustration of the type rule.
Worked example: arranging items on a shelf
A shelf has 5 distinct products. In how many different orders can they be placed in a row?
The answer is 5!:
import math
arrangements = math.factorial(5)
print(arrangements) # 120If the warehouse manager decides to put only the first 3 positions in a promotional display order, the question changes to "how many ordered selections of 3 from 5", which is 5! / 2!:
print(math.factorial(5) // math.factorial(2)) # 60Note the use of //: dividing two integers with / would give the float 60.0, while // keeps the exact integer. This is a typical exam detail about types.
hypot() and distances
For a right triangle with legs a and b, the hypotenuse is sqrt(a**2 + b**2). The function math.hypot(a, b) computes the corresponding Euclidean length as a float, and it is more robust for very large or very small numbers because it avoids intermediate overflow or underflow.
import math
print(math.hypot(3, 4)) # 5.0
print(math.hypot(5, 12)) # 13.0
print(math.sqrt(3**2 + 4**2)) # 5.0The result is a float, even when the numbers are whole. Since Python 3.8, hypot also accepts more than two arguments, giving the Euclidean length of the vector, for example math.hypot(3, 4, 12) is 13.0.
Worked example: forklift distance
Problem. A forklift starts at shelf position (x=1, y=1) and must go to position (x=7, y=9), measured in metres. What is the straight-line distance?
Step 1: find the differences. dx = 7 - 1 = 6, dy = 9 - 1 = 8.
Step 2: apply the formula. The distance is sqrt(6**2 + 8**2) = sqrt(36 + 64) = sqrt(100) = 10.
Step 3: code.
import math
x1, y1 = 1, 1
x2, y2 = 7, 9
distance = math.hypot(x2 - x1, y2 - y1)
print(distance) # 10.0Output: 10.0.
Why not another approach? Writing (x2 - x1) ** 2 + (y2 - y1) ** 2 gives 100, which is the squared distance, a frequent mistake. Using math.sqrt(dx + dy) forgets to square the differences and would give sqrt(14). Passing the points instead of the differences, math.hypot(7, 9), computes the distance from the origin to (7, 9), not from (1, 1). The function is only a hypotenuse calculator; you must supply the legs.
Worked example: truncating a negative sensor reading
Problem. A sensor logs a temperature change of -7 degrees spread over 2 equal steps. A developer wants "the whole number of degrees per step, dropping the fraction". Which function should be used, and what do the three candidates return?
Step 1: compute the exact value. -7 / 2 = -3.5.
Step 2: evaluate each candidate.
import math
value = -7 / 2
print(math.trunc(value)) # -3
print(math.floor(value)) # -4
print(math.ceil(value)) # -3
print(round(value)) # -4Step 3: choose. "Dropping the fraction" means moving toward zero, so math.trunc (result -3) is correct. floor gives -4 because it moves toward negative infinity, and round(-3.5) also gives -4, because the tie goes to the even neighbour. ceil happens to return -3 here, but it would be wrong for a positive value such as 3.5, where it gives 4. Only trunc is correct for both signs.
math versus the built-in round()
round() is not in math; it is a built-in function. Its behaviour differs from the three functions above in two important ways.
1. Ties go to the nearest even integer. When the fractional part is exactly 0.5, round() picks the even neighbour (often called banker's rounding):
print(round(0.5)) # 0
print(round(1.5)) # 2
print(round(2.5)) # 2
print(round(-0.5)) # 0
print(round(-2.5)) # -22. It can round to a number of digits and the return type depends on the arguments.
print(round(2.675, 2)) # 2.67
print(round(1234, -2)) # 1200
print(type(round(2.5))) # <class 'int'>
print(type(round(2.5, 0))) # <class 'float'>For a built-in float, omitting ndigits gives an int. Specifying ndigits, including 0, gives a float. Other numeric types can define their own rounding behavior. The value 2.675 becomes 2.67, not 2.68, because the decimal number cannot be stored exactly in binary floating point (the stored value is slightly below 2.675). This is a floating-point effect and not a bug in round.
| Function | Direction | Return type for a float argument | Example with 2.5 |
|---|---|---|---|
math.ceil |
toward +infinity | int |
3 |
math.floor |
toward -infinity | int |
2 |
math.trunc |
toward zero | int |
2 |
round (one argument) |
nearest, ties to even | int |
2 |
round(x, 0) |
nearest, ties to even | float |
2.0 |
A note on the power function
math.pow(2, 3) returns the float 8.0, while the operator 2 ** 3 and the built-in pow(2, 3) return the integer 8. The math version always works with floats.
Choosing the function
| Requirement in plain words | Function |
|---|---|
| "Enough containers", "at least", "round up" | math.ceil |
| "Complete units only", "round down" (non-negative values) | math.floor |
| "Drop the decimals", symmetric around zero | math.trunc |
| "Nearest value" for display or reports | round |
| "Number of orderings" | math.factorial |
| "Straight-line distance" | math.hypot |
Common pitfalls and exam tips
- Exam tip: For negative numbers, draw a number line.
floorgoes left,ceilgoes right,truncgoes toward zero. - Exam tip:
math.ceil,math.floorandmath.truncreturnint;math.sqrtandmath.hypotreturnfloat;math.factorialreturnsint. - Pitfall: Using
round()when the requirement says "enough boxes" or "at least". That needsceil. - Pitfall: Expecting
round(2.5)to be3. It is2. - Pitfall: Passing a float to
factorial. It raisesTypeError. - Pitfall: Expecting
math.sqrt(-4)to give a complex result. It raisesValueError. - Pitfall: Forgetting that
math.hypot(x, y)wants the legs, not the endpoints. - Exam tip: For the demonstrated
sqrtdomain failure, catchValueError. The required handler depends on the operation and argument. See handling Python exceptions. - Pitfall: Assuming
int()andmath.floor()are the same. They differ for negative numbers (int(-2.7)is-2,math.floor(-2.7)is-3).
Mini case study: a loading-dock calculator
A loading dock uses this script to plan pallets. Each pallet carries 48 cartons. The dock receives 1 000 cartons today, and a truck must cover a route from the dock at (0, 0) to a gate at (120, 90) metres.
import math
cartons = 1000
pallets = round(cartons / 48)
route = math.sqrt(120 + 90)
print(pallets)
print(route)A supervisor says earlier orders sometimes needed more pallets than the script allocated, and today’s route length looks wrong.
Questions. What does the script print? What two mistakes does it contain? Write the corrected version and its output.
Solution.
1000 / 48 = 20.8333..., soround(...)gives21. The printed route ismath.sqrt(210) = 14.491376746189438. (Output:21then14.491376746189438.)- Mistake one: for pallet capacity the operation must round up. Today
roundhappens to give 21, the same asceil(20.83), so the bug stays hidden. With 970 cartons the ratio is 20.208…,roundgives 20 pallets and 10 cartons are left without a pallet, whereasmath.ceilgives 21. The requirement "enough pallets" must be written withmath.ceil. - Mistake two: the route formula adds the legs instead of their squares. The correct expression is
math.hypot(120, 90). - Corrected code:
import math
cartons = 1000
pallets = math.ceil(cartons / 48)
route = math.hypot(120 - 0, 90 - 0)
print(pallets) # 21
print(route) # 150.0The route is exactly 150 m: the legs 120 and 90 are 30 times 4 and 30 times 3, a scaled 3-4-5 triangle. The supervisor's second complaint is explained, and the first is a latent defect that appears when the ratio has a fractional part below 0.5.
Key terms
math.ceil(x): smallest integer greater than or equal tox.math.floor(x): largest integer less than or equal tox.math.trunc(x): integer part, discarding the fraction (toward zero).math.sqrt(x): square root as a float,ValueErrorfor negatives.math.factorial(n): product 1 tonas an integer, defined for whole numbersn >= 0.math.hypot(a, b): length of the hypotenuse for legsaandb.- Domain error: a
ValueErrorraised when an argument lies outside a function's mathematical domain. - Banker's rounding: rounding ties to the nearest even integer, as in the built-in
round().
Summary checklist
- I can state what
ceil,floorandtruncreturn for positive and negative numbers. - I know which
mathfunctions returnintand which returnfloat. - I can predict
ValueErrorversusTypeErrorforsqrtandfactorial. - I can compute a distance with
hypotfrom two points. - I can explain why
round(2.5)is2and howround()differs frommath.ceil. - I can pick the right function for "enough boxes", "whole days elapsed" and "drop the decimals".
Official sources
- Python Institute, PCAP-31-03 syllabus: https://pythoninstitute.org/pcap-31-03-exam-syllabus (opens in a new tab)
- Python documentation, the
mathmodule: https://docs.python.org/3.14/library/math.html (opens in a new tab) - Python documentation, built-in
round(): https://docs.python.org/3.14/library/functions.html#round (opens in a new tab)
