Python Basics: Everyday Calculations with math
How many boxes do you need? Are two measurements close enough? How far apart are two points? Python’s standard-library math module provides useful helpers for these small calculations.
Before you start
These independent examples were tested on Linux with Bash, Python 3.12.14 and Python 3.13.5. No extra packages or environment variables are required. The commands use python3; replace it with python3.13 to use that interpreter.
Create a fresh working directory in one Bash session:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save each source block here using its stated filename. Avoid math.py, which would shadow the standard-library module. These programs only print results; the source files are the only files to clean up.
Round up a packing estimate
Save as demo_math_1.py:
import math
items_per_box = 6
for items in (0, 12, 13):
boxes = math.ceil(items / items_per_box)
print(f"{items} items: {boxes} boxes")
print("Round down -1.2:", math.floor(-1.2))
print("Round up -1.2:", math.ceil(-1.2))Run it:
python3 demo_math_1.pyOutput:
0 items: 0 boxes
12 items: 2 boxes
13 items: 3 boxes
Round down -1.2: -2
Round up -1.2: -1ceil() rounds toward positive infinity; floor() rounds toward negative infinity. The negative example makes that direction visible. Our packing inputs are nonnegative and the box capacity is positive. Validate those constraints when accepting user input. For very large integer counts, use (items + items_per_box - 1) // items_per_box to avoid floating-point division.
Compare measurements with a tolerance
Save as demo_math_2.py:
import math
total = 0.1 + 0.2
print("Exact comparison:", total == 0.3)
print("Close comparison:", math.isclose(total, 0.3))
for offset in (0.0004, 0.002):
acceptable = math.isclose(offset, 0.0, rel_tol=0.0, abs_tol=0.001)
print(f"Offset {offset:.4f}: acceptable={acceptable}")Run it:
python3 demo_math_2.pyOutput:
Exact comparison: False
Close comparison: True
Offset 0.0004: acceptable=True
Offset 0.0020: acceptable=FalseMany decimal fractions are approximate as binary floats. isclose() checks a tolerance rather than exact equality. Here, a sensor’s allowed offset is 0.001 units. Setting rel_tol=0.0 makes this an absolute-only check. Choose tolerances from your application’s requirements; comparisons near zero generally need a positive absolute tolerance.
Measure a movement on a grid
Save as demo_math_3.py:
import math
def movement_length(dx, dy):
if not all(math.isfinite(value) for value in (dx, dy)):
raise ValueError("movement must be finite")
return math.hypot(dx, dy)
for dx, dy in ((3.0, 4.0), (0.0, 0.0), (-3.0, 4.0)):
print(f"Movement ({dx:.1f}, {dy:.1f}): {movement_length(dx, dy):.1f}")
for invalid in (math.inf, math.nan):
try:
movement_length(invalid, 4.0)
except ValueError as error:
print(f"Rejected: {error}")Run it:
python3 demo_math_3.pyOutput:
Movement (3.0, 4.0): 5.0
Movement (0.0, 0.0): 0.0
Movement (-3.0, 4.0): 5.0
Rejected: movement must be finite
Rejected: movement must be finitehypot() calculates the straight-line length from coordinate differences. Both axes must use the same unit. The wrapper deliberately rejects infinity and NaN; these caught failures demonstrate our input policy. This example assumes numeric inputs. It does not calculate road distances or distances on Earth’s surface.
Clean up
In the same Bash session, remove only the files you created, then the empty directory:
rm -- demo_math_1.py demo_math_2.py demo_math_3.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf rmdir reports that the directory is not empty, inspect its contents rather than deleting other files blindly.
References
Acknowledgements
This post was created with assistance from AI.