Back to the Question: Rounding and Machine Epsilon
The stored values behind the opening question, a tie resolved to even, machine epsilon, and how the gap between numbers grows with their size.
Last updated:
In this lecture we learn to:
- answer “why is 0.1 + 0.2 not 0.3” with exact numbers: stored values, an exact sum and a tie;
- bound the rounding error of a stored number and say what machine epsilon tells you about it;
- explain why the gaps between stored numbers grow with their size, and when adding a small number changes nothing.
What we take from “How Computers Store Numbers”
The lecture How Computers Store Numbers built the format. Three takeaways from it are needed here:
- a normal number is stored as a sign, an exponent with a bias and a fraction, and it stands for ;
- binary64 has one sign cell, 11 exponent cells and 52 fraction cells;
- the decimal has a binary expansion that never ends, so it is not stored exactly.
Back to the question: why
In one sentence: 0.1 and 0.2 are both stored a little too large, and 0.3 is stored a little too small.
The exact sum of the two stored numbers lands exactly halfway between two adjacent stored numbers, and the tie is broken upwards.
The result is the stored number that comes right after the stored 0.3, so the two numbers differ.
We can now answer the opening question with exact numbers. Every normal binary64 number (one with an unstored leading 1, that is, not zero, subnormal, infinity or NaN) can be written as a whole number of equal small units, where the unit is the value of the last fraction bit.
This unit is constant between two consecutive powers of 2 and doubles at every power of 2, so larger numbers lie farther apart.
We measure the errors in units of , the unit of numbers between and , such as 0.1.
Predict: the bits of 0.1 after place 52 are Will 0.1 be rounded up or down?
-
Storing 0.1. From the lecture How Computers Store Numbers, in binary never ends, so it is rounded to 53 significant bits.
This is how we find the stored value:-
Move the point four places to get a 1 before it: .
-
There are 52 fraction bits, that is, 13 groups of four. The first twelve groups are , and the 13th group is followed by after place 52.
-
What is left after the 52nd bit is of the last bit’s unit, :
more than half: the next bit is 1 and another 1 follows, so we round up.
The last group becomes . -
Rounding added a whole unit in place of the that was cut, that is, of :
The stored value is slightly larger than 0.1. On the page Computing the stored representation: two methods it is also computed in another way.
Predict: . By how many does the stored 0.2 differ from 0.2?
-
-
Storing 0.2. Doubling changes only the exponent, so . Now the last place is and rounding added of it:
-
Adding the two stored numbers, exactly.
This exact sum has to be stored, so it is rounded to a nearby stored number.
We need to know where the stored numbers near 0.3 are.Predict: the bits cut off from 0.3 are More than half of the last place, or less?
Which way will 0.3 be rounded?
-
Storing 0.3. In binary . The 13 groups are the 52 fraction bits, and the cut-off part is of the last place, less than half, so we round down.
The last place here is , so:The stored neighbour above it is one place higher: .
Predict: the exact sum is , and the two stored numbers around it are and .
Which of them is it closer to?
-
A tie. The exact sum is above and also below the neighbour above it, that is, exactly halfway.
The IEEE 754 rule (round to nearest, ties to even) picks the neighbour whose last fraction bit is 0.
The fraction of ends in (last bit 1) and that of the neighbour above ends in (last bit 0), so the tie goes up:
The computed sum and the stored 0.3 are neighbours, one gap of apart.
So 0.1 + 0.2 == 0.3 is False, and Python prints the sum as 0.30000000000000004.
Nothing malfunctioned: each step followed the rules exactly.
Compare 0.5 + 0.25 == 0.75: all three numbers are stored exactly and the sum fits, so no rounding happens at all.
Python can show what is stored for 0.1, that is, the first step.
The method .hex() writes a float in hexadecimal (base 16), and Decimal(x) from the standard decimal module converts a float to a decimal number without rounding, so it reveals the exact stored value:
from decimal import Decimal
print((0.1).hex())
print(Decimal(0.1))
0x1.999999999999ap-4
0.1000000000000000055511151231257827021181583404541015625
The first line says . Each hexadecimal digit is four bits, so the 13 digits after the point are the 52 fraction bits.
Each group of the first step is the hexadecimal digit 9, and the last group is a:
that is the rounding up. The second line is the stored value we found, .
The next explorer shows the three fields at their real lengths.
Choose binary64 and jump to 0.1: the fraction digits are again and again, and at the end the last group is instead of .
That is the rounding up we found in the first step. Flip the last fraction bit and see how much the value changes.
When the number is 1, the row “Gap to the next number here” is the machine epsilon of the chosen format:
in binary16, in binary32 and in binary64.
Check the arithmetic yourself; Fraction(x) (from the fractions module) is the exact value of the stored number x:
from fractions import Fraction
# the exact sum of the two stored numbers
exact_sum = Fraction(0.1) + Fraction(0.2)
# exactly half a gap above the stored 0.3
print(exact_sum - Fraction(0.3) == Fraction(1, 2**55))
print(0.1 + 0.2 == 0.30000000000000004)
True
True
Rounding and machine epsilon: how large can the error be?
A note on rounding. When a number lies between two stored numbers, IEEE 754 stores the nearer one.
In the rare case of an exact tie it chooses the one whose last fraction bit is 0, for example and not (“round to nearest, ties to even”).
We write for the stored number nearest to (fl stands for floating point, not for floor).
So the absolute error of storing a normal number is at most half the gap to its neighbour, and is at most :
Dividing by gives the relative error:
Some books call itself the machine epsilon; in these notes, as in Python’s sys.float_info.epsilon, it is the gap between 1 and the next number.
1. A fixed relative accuracy, in every size. One rounding changes a normal binary64 number by a relative amount of at most .
This is below , the bound for rounding to 16 significant decimal digits, whatever the size of the number.
This is a statement about relative error, not about digits after the decimal point.
2. Large numbers lose small additions. Near the gap between stored numbers is 2, so adding 1 changes nothing:
print(1e16 + 1 == 1e16) # True
True
The exact sum lies exactly halfway between two stored numbers, and the tie goes to the one whose last fraction bit is 0, which is .
More generally, a number smaller than half the gap beside a larger number disappears when it is added to it:
we say it is absorbed.
Choose a format, and zoom in or out to see all the numbers that the format stores, and how dense they are in different parts of the number line:
Explore how the gap changes with the size of the number, and where adding 1 stops having any effect:
| Number | Gap to the next binary64 number | Is x + 1 a different number? |
|---|---|---|
| 1 | yes | |
| yes | ||
| 2 | no | |
| 2 | no | |
| no |
Comparing computed numbers
Two numbers that are equal on paper can differ by a few units of rounding, as 0.1 + 0.2 and 0.3 do.
A program that compares computed numbers therefore asks whether they are close, not whether they are equal.
Python’s function math.isclose, called like this:
math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0)
answers True exactly when
Here rel_tol is the largest difference we accept as a fraction of the larger of the two numbers (a relative bound), and abs_tol is a fixed difference in the units of the numbers (an absolute bound).
We call the pair the comparison tolerance. It is not the tolerance of an iteration:
that one is the threshold that stops a method (see the course conventions), while the comparison tolerance decides whether two numbers count as equal.
With only rel_tol, a number can be close to only if it equals :
for the right-hand side is , which is smaller than whenever rel_tol is below 1.
This is why the zero case needs abs_tol:
import math
# True: the difference is 5e-10 of the size
print(math.isclose(1e6, 1e6 + 0.0005))
# False: relative to 0 any difference is large
print(math.isclose(1e-15, 0.0))
# True
print(math.isclose(1e-15, 0.0, abs_tol=1e-12))
True
False
True
A tolerance cannot be smaller than the gap
Neighbouring binary64 numbers differ, relative to their size, by at least .
A comparison tolerance (or a stopping threshold) below the gap beside the numbers can therefore be met only by numbers that are equal.
Near 1 the gap is , so demanding an error below for a root near 1 cannot succeed unless the stored number is the exact answer.
The rule: choose tolerances above times the size of the numbers involved.
Rounding a typed decimal
Python’s round(x, n) returns x rounded to n digits after the decimal point:round(1.26, 1) is 1.3. It acts on the stored binary value of x, not on the digits that were typed.
A decimal such as , halfway between and , looks like a tie, but it is a true tie only when the typed value is exactly representable, that is, when it is a fraction whose denominator is a power of 2.
For example and are stored exactly, so round(0.125, 2) is a real tie and goes to the even digit, giving 0.12.
The number has the denominator , which is not a power of 2, so it is not stored exactly.
The stored value is , below the midpoint, and round(2.675, 2) returns 2.67.
The same reasoning decides every decimal tie: the result depends on which side of the midpoint the stored number falls, which looks random from the digits alone.
For money, a cash register must follow a rounding rule fixed in advance.
In Israel, according to the Bank of Israel announcement on cancelling the 5 agorot coin (1 January 2008), only the total of a cash payment is rounded, to ten agorot:
1 to 4 agorot round down and 5 or more round up (17.04 becomes 17.00, and 17.07 becomes 17.10).
A total that ends in 5 agorot, such as 17.05, is exactly halfway between two totals of ten agorot.
That is a tie, and the rule says it rounds up. Let us check what round does with such totals:
for x in [17.05, 17.15, 17.25, 17.45]:
print(x, round(x, 1))
17.05 17.1
17.15 17.1
17.25 17.2
17.45 17.4
| Total | round(x, 1) | The rule | Why |
|---|---|---|---|
| 17.05 | 17.1 | 17.1 | agrees by chance: the stored value is above the midpoint |
| 17.15 | 17.1 | 17.2 | the stored value is below the midpoint |
| 17.25 | 17.2 | 17.3 | the value is stored exactly, and round settles the tie to the even digit, like 0.125 becoming 0.12 earlier |
| 17.45 | 17.4 | 17.5 | the stored value is below the midpoint |
round acts on the stored binary value and not on the digits that were typed, so it does not follow the rule, and a cash register should not rely on it.
Python’s decimal module keeps decimal digits exactly and lets us name the rule.Decimal('17.05'), written as a string, holds the typed digits exactly, the method quantize rounds a decimal to the shape of its argument (Decimal('0.1') means one digit after the point), and rounding=ROUND_HALF_UP names the rule:
a tie goes up, away from zero.
from decimal import Decimal, ROUND_HALF_UP
for s in ['17.05', '17.15', '17.25', '17.45']:
print(s, Decimal(s).quantize(Decimal('0.1'), rounding=ROUND_HALF_UP))
17.05 17.1
17.15 17.2
17.25 17.3
17.45 17.5
Here the typed digits are kept exactly, so 17.05, 17.15, 17.25 and 17.45 are real ties, and the rule we named decides them, unlike round.
A formula for the gap between a stored number and its neighbor
So far we read the gaps off the number line of the tiny format.
Here we compute them for any format, without a figure, and obtain an explanation of two patterns we saw:
the absolute gap grows with the size of the numbers, and the relative gap stays within a fixed range.
In a format with fraction bits, a number of the form equals , where is the whole-number value of the fraction bits.
It is a whole multiple of , the value of the last fraction bit.
The next stored number is obtained when grows by 1, that is, when the number grows by .
The gap between two adjacent stored numbers with the same exponent is therefore
We check the formula in the tiny format () and in binary64 ():
- In the tiny format, between 4 and 8 we have , so the gap is
- In the tiny format, between 1 and 2 we have , so the gap is
- In binary64, near 1 the gap is
- In binary64, near we have , so the gap is
The formula explains both patterns. The absolute gap depends only on , so it is constant between two consecutive powers of 2 and doubles when grows by 1.
For normal numbers the relative gap is , and as ranges from 1 to 2 it ranges from to (in the tiny format, from to ).
Near 1, that is when , the gap is .
Machine epsilon in the IEEE formats
Machine epsilon is the gap near 1, and by the gap formula with it equals .
We substitute the number of fraction bits of each format from the table of the standard:
| Format | Fraction bits | Machine epsilon |
|---|---|---|
| binary16 (half precision) | ||
| binary32 (single precision) | ||
| binary64 (double precision) |
In binary64, machine epsilon is , and since this is also the relative gap near 1, a stored binary64 number represents the number we asked for to about 16 significant decimal digits.
Why this gap matters
When we build a method that solves a problem, it computes step by step and stops when the result is close enough to the answer.
Here the computer limits us: stored numbers are not a continuum, and between two neighboring stored numbers there is no stored number at all.
So there is no point in demanding that a computation come closer than this gap:
the demand will never be met, and the method will keep running without stopping, or stop only by accident.
The gap itself grows with the size of the numbers, but the gap relative to the size of the number, that is, the relative error caused by a jump of one gap, hardly changes.
Near 1 the gap and the relative error are the same, so machine epsilon is the unit of accuracy that fits every size:
when the numbers are of size , we will not ask for a closeness smaller than .
For example, in binary64 near 1 we will not ask for a closeness smaller than , and near not smaller than about .
The same principle applies to comparison: two computed numbers that differ by one gap or less are, as far as the computer is concerned, almost the same number.
Continue learning
The rounding puzzle began as two LinkedIn posts, the puzzle and its discussion, whose comments raised the questions these lessons answer.
The next step is the page Computing the Stored Representation: Two Methods, which finds the stored value of 0.1 in two ways, step by step, and uses it for two sums that look alike but behave differently.
After it comes the practice session for both lectures: the inspector with conclusions you commit to, the limits of binary64, safe comparison of numbers, and the rounding puzzle.
After it, the lecture Small Errors, Big Consequences: The Patriot Clock studies how these small rounding errors behave when we compute:
how they accumulate, and why subtracting nearly equal numbers can destroy accuracy.
For a deeper look:
- David Goldberg, What Every Computer Scientist Should Know About Floating-Point Arithmetic, ACM Computing Surveys, 1991.
- The Python tutorial chapter Floating-Point Arithmetic: Issues and Limitations, and the note on
roundin the built-in functions reference. - Real Python, How to Round Numbers in Python.
- Kong, Siauw and Bayen, Python Programming and Numerical Methods, the course textbook, which has a chapter on number representation and error.