Python Float Arithmetic and Approximation
Calculate fractional quantities
A floating-point number (float) can represent fractional quantities, such as 1.5. A decimal point in an ordinary numeric literal makes it a float, even in 2.0. For built-in arithmetic with an integer and a float, addition, subtraction and multiplication produce a float.
Four lengths of 1.5 total 6.0. Adding two to 1.5 gives 3.5. The .0 in the first output is consistent with the float result.
Why some results are approximate
total = 0.1 + 0.2print(total)print(total - 0.3)On the tested CPython runtime the first line is slightly above 0.3. The second line uses scientific notation: e-17 means times ten to the power −17. Most decimal fractions are approximations in binary floating-point storage. This is not a mistake in addition. When comparing measured values, choose an acceptable tolerance (maximum difference), rather than expecting exact equality. Comparison operations are covered later; the example above just examines the difference.
Choose a suitable numeric model
For a price defined in whole cents, storing 125 cents avoids the binary approximation of decimal currency arithmetic for this calculation. More general decimal calculations can use the decimal module, covered later. Merely printing fewer digits does not make the stored float exact.
Practice
Calculate the length of five pieces of 1.25 units each. Then compare the result of 0.1 + 0.2 with the value you expect mathematically.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Float arithmetic and precision
Check your understanding of float arithmetic.
Which literal represents a float?
What is printed?
print(1.25 * 4)Why can the result of 0.1 + 0.2 differ slightly from 0.3?
Which model can exactly store a whole-cent price of 199 cents for integer calculations?
What does reducing the number of displayed digits achieve?