Lesson · Language Fundamentals
Numeric Semantics & Math
60 min readNumeric Semantics & Math
Numeric code is reliable only when you understand the model behind each number type. This lesson covers integer precision, floating-point error, rounding, decimal arithmetic, and exact fractions.
Learning goals
- Compute with
/,//,%, anddivmod()and explain how each handles integers and negatives. - Explain why Python integers are arbitrary precision, and what growing values cost.
- Demonstrate a floating-point approximation (
0.1 + 0.2) and choose between==,math.isclose(),Decimal, andFractionfor a task. - Use
round()andmath.isclose(), and say why the tie rule is round-to-even and why rounding a float cannot repair its representation error. - Choose exact tools deliberately:
Decimalfor decimal values such as money,Fractionfor ratios,mathfor float-based functions.
Mental model
Read the diagram as a choice, not a hierarchy: the worked example runs the same kind of addition through three of these lanes to show how the result changes with the tool.
Mental model
read it top to bottom
whole numbers, any size int exact, unbounded measurements, approximations float binary, fast, tiny errors possible exact decimals (money) Decimal base-10, exact for decimal values exact ratios (1/3) Fraction exact rationals
Core idea
Numbers in Python come with different accuracy contracts: int is exact without limit, float is fast and binary-approximate, and the standard library adds Decimal for exact base-10 values and Fraction for exact ratios. Numeric bugs are usually a mismatch between the contract a task needs and the type it was given, so choosing the type is the first decision of the lesson, not the last.
Integer arithmetic
Integer arithmetic is exact within available memory. Division with / still produces floating point, while //, %, and integer pow retain integer-oriented semantics where applicable.
Arbitrary-precision integers
Python integers expand to represent values larger than fixed 32-bit or 64-bit machine integers, subject to available memory. Operations can therefore become more expensive as values grow.
Floating-point behavior
Python float normally uses IEEE 754 binary floating-point. Many decimal fractions cannot be represented exactly, so calculations can contain small representation errors.
Rounding
Rounding is a policy, not just a function call. Python's built-in round() uses round-to-even behavior for ties in common cases; business rules can require different decimal policies.
round()
round(number, ndigits=None) returns the nearest whole number when ndigits is omitted (an int), or a value with ndigits decimal places when it is given. Ties go to the even digit, and the input's stored value decides the result: round(2.675, 2) is 2.67 because the float is slightly below 2.675.
abs()
abs(x) returns the absolute value of a number, preserving the type for ints and floats. For a complex it returns the magnitude, and for your own classes it calls __abs__, so the operation is protocol-driven rather than limited to built-in numbers.
divmod()
divmod(a, b) returns the pair (a // b, a % b) in one call, so quotient and remainder come from the same operation. It raises ZeroDivisionError when b is zero and follows the same floor-division rule as // and %.
pow()
pow(base, exp) is the function form of base ** exp, and pow(base, exp, mod) computes the power modulo mod without building the full huge integer. The three-argument form is integer-only and is the efficient tool for modular arithmetic.
math
math is the standard library module of mathematical functions and constants, from sqrt, sin, and log to floor, gcd, and isclose, plus pi and tau. Most of it operates on floats and returns floats, and domain violations raise ValueError rather than returning a special value.
decimal
decimal provides Decimal, an exact base-10 number type with a configurable context for precision and rounding. Build values from strings (Decimal("0.10")) to keep the decimal digits exact, use quantize to fix a number of places, and prefer it for money and any rule expressed in decimal digits.
fractions
fractions provides Fraction, an exact ratio of two integers, so Fraction(1, 10) + Fraction(2, 10) is exactly 3/10. Fractions normalize automatically, stay exact through multiplication and division, and convert to floats only on request, which makes them the tool for ratios that must not drift.
Comparing floating-point values safely
For approximate numeric results, compare within an acceptable tolerance instead of expecting exact equality. math.isclose() encodes this intent clearly.
Walkthrough
0.1and0.2enter the first sum as binary approximations, so0.1 + 0.2prints0.30000000000000004; the error is small but real.math.isclose(0.1 + 0.2, 0.3)asks whether the two floats are near each other within a relative tolerance and printsTrue, which is the comparison to use for computed floats.Decimal("0.1") + Decimal("0.2")builds both values from strings, so the base-10 addition is exact and prints0.3. Note the string constructor:Decimal(0.1)would inherit the float's stored error instead.Fraction(1, 10) + Fraction(2, 10)adds exact rationals and prints3/10; the result stays a fraction until a float is explicitly requested.- Predict before running: which lines print exactly
0.3, and whatDecimal(0.1)would print in place ofDecimal("0.1").
Experiments to try
- Print
Decimal(0.1)andDecimal("0.1")side by side and explain why the first shows a long tail of digits. - Call
round(2.675, 2),round(2.5), andround(3.5); connect the results to ties-to-even and to2.675being stored slightly below its decimal spelling. - Compute
1/3as a float, asFraction(1, 3), and asDecimal(1) / Decimal(3); line up the three outputs and say what each tool preserved. - Compare
divmod(17, 5)with17 // 5, 17 % 5; then computepow(2, 10)andpow(2, 10, 1000)and explain what the third argument adds.
Common mistakes
- Comparing computed floats with
==: sums such as0.1 + 0.2carry tiny representation error, so==fails wheremath.isclosesucceeds; exact equality is for values not computed through float math. - Using binary
floatfor money: small decimal errors accumulate across many operations, whileDecimal("0.10")keeps cents exact; choose the type for the domain, not from habit. - Assuming
roundrounds halves away from zero: ties go to the even digit (round(2.5)is2), and rounding cannot repair a value that is already slightly off (round(2.675, 2)is2.67). - Expecting
/to stay integral on ints: true division always produces afloat, so very large ints lose precision through/; use//orFractionwhen the division must stay exact.
Practice: Easy
- Evaluate
7 / 2,7 // 2,7 % 2, anddivmod(7, 2); state which results are ints, which are floats, and how they relate. - Print
0.1 + 0.2, thenround(0.1 + 0.2, 2), thenmath.isclose(0.1 + 0.2, 0.3); explain why only the last one is a safe comparison. - Compute
Decimal("0.1") + Decimal("0.2")andFraction(1, 10) + Fraction(2, 10); print each result and its type.
Practice: Medium
- Add
0.1ten times in a loop and compare the total with1.0using==thenmath.isclose; print both answers and explain the difference. - Round
2.675to two decimals,2.685to two, and2.5to zero; explain each result using ties-to-even and binary representation. - Sum
1/3 + 1/3 + 1/3withFractionand with floats; state which version equals exactly1and why.
Practice: Hard
- Design a money calculator that stores amounts as
Decimalbuilt from strings, adds three amounts, and formats the total withquantize(Decimal("0.01")); explain whyfloatwas the wrong choice at each step. - Compare
pow(2, 1000)with2 ** 1000, then verifypow(2, 100, 13)against(2 ** 100) % 13; explain why the three-argument form matters for cryptographic-scale numbers. - Write a tolerance rule for a measurement pipeline with two test cases, one near
1.0and one near1e-9; justify your absolute or relative tolerance by runningmath.isclosewith its defaults and with your values.
Lesson checklist
- I can explain what
/,//,%,divmod(), and three-argumentpow()each return. - I can show a float sum that is not exact and compare it safely with
math.isclose(). - I can choose
DecimalorFractionfor an exact task, including buildingDecimalfrom strings. - I can say why
round()ties go to even and why it cannot repair representation error.
Remember
Numbers are chosen, not inherited: `int` is exact and unbounded, `float` is fast and approximate for decimals, `Decimal` is exact base-10, and `Fraction` is exact ratio. Keep `math.isclose` for comparing computed floats and pick the type that matches the accuracy the task actually needs.
Interview angles
What is the main purpose of **Integer arithmetic**?+
Integer arithmetic is exact within available memory. Division with / still produces floating point, while //, %, and integer pow retain integer-oriented semantics where applicable.
What should you pay attention to when using **Arbitrary-precision integers**?+
Python integers expand to represent values larger than fixed 32-bit or 64-bit machine integers, subject to available memory. Operations can therefore become more expensive as values grow.
How does **Floating-point behavior** fit into this lesson?+
Python float normally uses IEEE 754 binary floating-point. Many decimal fractions cannot be represented exactly, so calculations can contain small representation errors.
Why is `round(2.675, 2)` equal to `2.67` rather than `2.68`?+
The float nearest to 2.675 is actually a hair below it, so rounding the stored value correctly goes down; the decimal 2.675 was never represented exactly. Use Decimal("2.675") and quantize when the decimal digits themselves are the requirement.