Python fractions Module — ELI5
Try this on a calculator: 1 ÷ 3 = 0.333333... — the threes go on forever. Your calculator has to stop somewhere and round. Now multiply that rounded number by 3 and you get 0.999999 instead of 1. Something was lost.
Computers have the same problem with decimal numbers. 0.1 + 0.2 in Python doesn’t give you exactly 0.3 — it gives you 0.30000000000000004. Tiny error, but it adds up.
Python’s fractions module avoids this entirely. Instead of turning 1/3 into a decimal, it keeps it as a fraction: numerator 1, denominator 3. When you multiply by 3, you get 3/3, which is exactly 1. No rounding, no tiny errors.
Think of it like pizza. If you cut a pizza into 3 equal slices, each slice is exactly one-third. You don’t need to measure it to fifteen decimal places — it’s just one of three equal pieces. Fractions work the same way.
This matters whenever exactness counts. Recipes that need precise measurements, financial calculations where pennies matter, or any math where tiny rounding errors can snowball into visible mistakes.
Most of the time, regular decimals are fine. But when you need the answer to be exactly right — not “close enough” — fractions deliver.
The one thing to remember: Python’s fractions module keeps numbers as exact ratios (like 1/3) instead of rounded decimals, so your math stays perfectly accurate.
See Also
- Python Atexit How Python's atexit module lets your program clean up after itself right before it shuts down.
- Python Bisect Sorted Lists How Python's bisect module finds things in sorted lists the way you'd find a word in a dictionary — by jumping to the middle.
- Python Contextlib How Python's contextlib module makes the 'with' statement work for anything, not just files.
- Python Copy Module Why copying data in Python isn't as simple as it sounds, and how the copy module prevents sneaky bugs.
- Python Dataclass Field Metadata How Python dataclass fields can carry hidden notes — like sticky notes on a filing cabinet that tools read automatically.