Practice: How Accurate Is the Computer?
Inspect stored bits, explore the limits of binary64, compare floating-point numbers safely, and solve the rounding puzzle: practice for the lecture “How Computers Store Numbers”.
Last updated:
After this practice session you will be able to:
- work out, and then check, which numbers a format stores exactly;
- say what happens at the limits of binary64: overflow, underflow and very small numbers;
- compare computed numbers safely, with a comparison tolerance that fits the numbers involved;
- convert a decimal number to binary and decode the sign, exponent and fraction fields of a stored number;
- explain a rounding result that looks wrong.
It follows the two lectures How Computers Store Numbers and Back to the Question:
read or attend them first.
Warm-up: what do you remember?
1. Which of these numbers is stored exactly in binary64?
A:
, and the denominator is a power of 2, so it ends in binary:
. It fits in the significand.
B:
Its binary expansion never ends, so it is rounded.
C:
Its binary expansion never ends either.
D:
In binary it is and never ends.
2. What does machine epsilon measure?
A: the smallest positive number a float can store
That is far smaller, about . Machine epsilon is a gap, not a size.
B: the largest possible error of any computation
Errors can grow far beyond it, as the Patriot lesson shows. The relative error of a single rounding is at most half of machine epsilon.
C: exactly
It is close to that order of magnitude, but it is a power of 2, .
D: the gap between 1 and the next larger stored number
This is the definition: in binary64.
Practice: converting and decoding
Solve each question on paper before you move on to the lab.
- Convert 13.375 to binary.
- Is 0.625 stored exactly in binary64? Justify using its fraction.
- In the tiny format of this lesson (one sign bit, three exponent bits with bias 3, three fraction bits), find the three fields for the number 6.
- In a format with one sign cell, three exponent cells (bias 3) and three fraction cells, a number is stored as
0 000 101: sign 0, exponent field 000, fraction field 101. A classmate reads it as .- a. Say why this is wrong and give the exponent that is really used.
- b. Find the stored value and the gap between this number and the next stored number.
- In a format with one sign cell, three exponent cells (bias 3) and three fraction cells, a number is stored as
1 000 011: sign 1, exponent field 000, fraction field 011. Find the value it holds. - A hypothetical format has one sign cell, four exponent cells with bias 7 and three fraction cells. Find its smallest positive normal number and its smallest positive subnormal number, as powers of 2, and say how many times larger the first is than the second.
The scientific calculator converts whole numbers between decimal, binary, hexadecimal and octal in BASE-N mode.
Try it on a number that is not in the questions above, and check that its binary expansion agrees with the calculation on paper.
Fractions, such as the part after the point in 13.375, are converted by repeated doubling, as in the lecture.
Hint for question 3
Write 6 as , then add the bias to and write the result with three bits.
Hint for questions 4 to 6
Look at the exponent field first. When it is all zeros, the number has no leading 1 in front of the fraction (the leading cell is 0), and the exponent that scales it is , not .
The unified formula is in IEEE 754. For question 6, find the smallest exponent field that is not all zeros, and then the gap between two neighbours at that size.
Solutions
- and , so .
- and the denominator is a power of 2, so it ends in binary: . It fits in the significand, so it is stored exactly.
- , so and the stored exponent is . The fraction bits are 100. The fields are sign 0, exponent 101, fraction 100. Check: .
- The exponent field is all zeros, so this is not a normal number. The reading makes two mistakes: it puts a leading 1 in front of the fraction, but here the leading cell is 0; and it uses the exponent , but for an all-zero exponent field the exponent is . The value is
The gap to the next stored number is (the next number is
0 000 110, which holds ). This is the same gap as just above , the smallest normal number (0 001 000): subnormal numbers continue the spacing of the smallest normal range down to 0, in steps of . - The sign is 1, so the number is negative. The exponent field is all zeros, so the exponent is and the leading cell is 0:
- The smallest exponent field that is not all zeros is , so the smallest normal number is . With the exponent field all zeros the exponent is also , the leading cell is 0, and the smallest nonzero fraction is (the last cell is 1). So the smallest positive subnormal number is . The first is times larger: the gap between neighbours below is , so is 8 gaps above zero.
Lab: what did the computer store?
Pick a number and a format. Before the inspector shows anything, reason it out:
can the number be written as a finite sum of powers of 2 that fits in the available bits, and is it inside the range?
Commit to a conclusion, and the inspector shows the exact stored bits, the value and the error, and tells you which step of the reasoning to revisit if your conclusion was off.
Afterwards, flip bits in the register to see what each one contributes.
Press Show how this is computed to see the steps of Method B for your number.
Without the lab. Here is the same inspection for two numbers in binary64.
The bits are grouped in fours so you can read them.
| 0.5 | 0.1 | |
|---|---|---|
| Sign | 0 | 0 |
| Exponent field | 01111111110 | 01111111011 |
| Fraction field | 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 | 1001 1001 1001 1001 1001 1001 1001 1001 1001 1001 1001 1001 1010 |
| Exact stored value | 0.5 | 0.1000000000000000055511151231257827… |
| Error (stored − typed) | 0 | about +5.55 × 10−18 |
The exponent field is the true exponent plus the bias 1023. For the exponent is , so the exponent field is and the fraction is empty.
For the exponent is , so the exponent field is .
For the repeating pattern was cut after 52 bits.
The last group rounded up from to , which is why the stored value is a little larger than .
The steps that lead to these bits are on the page Computing the Stored Representation: Two Methods.
Experiments to try. Each time, reason first and check afterwards:
- Many computers store time as the number of seconds since 1 January 1970. The moment 11 November 2026 at 08:30:00 (Israel time) is second 1794378600. Store the number in binary32. Is it stored exactly? If not, by how many seconds is the stored clock wrong?
- A GPS receiver reports a latitude of 32.0903 degrees (a point in Ramat Gan, Israel). Store the number in binary32. One degree of latitude is about 111 km on the Earth’s surface. By how many centimetres does the stored position move?
- Store 0.1 in binary32 and then in binary64. Which has the larger relative error?
- Store 9007199254740993, which is . What is stored instead, and why?
- Try 1e-320 and 1e400 in binary64, and then 1e-330.
Answers to the experiments
- The number is an integer, so it is a finite sum of powers of 2. But it lies between and , so it needs 31 significant bits, and binary32 has only 24 (the leading 1 and the 23 fraction bits). The seven lowest bits are not stored, so the stored numbers of this size are the multiples of . The nearest multiple is 1794378624, and that is the stored number: the stored clock is 24 seconds ahead, and all the moments in a span of 128 seconds are stored as the same number. binary64 has 53 significant bits, and it stores the number exactly.
- The stored number is 32.090301513671875, larger than the typed number by degrees. As a distance this is , so the stored position moves about 17 centimetres to the north. The number lies between and , so the last of the 23 fraction bits is worth degrees, about 42 centimetres: this is the gap between two adjacent stored latitudes, and binary32 cannot store a position more precisely than that.
- The relative error is about in binary32 and about in binary64: fewer fraction bits mean a larger error.
- The number 9007199254740992 is stored. From on, neighbouring binary64 numbers are 2 apart, so the odd integer lies exactly halfway between two stored numbers and is rounded to the neighbour whose last bit is 0 (the tie rule is in the answer to the opening question, in the lecture Back to the Question: Rounding and Machine Epsilon).
- 1e-320 is a subnormal number (it is stored, but with fewer significant bits), 1e400 overflows to infinity, and 1e-330 underflows to zero.
Addition explorer
The lecture explained why 0.1 + 0.2 == 0.3 is False. Now test your understanding on many cases.
Each case gives a format and two numbers. Before anything is shown, work out whether the comparison is True, which mechanism applies, and whether a tie occurs, and write your reason.
Only then lock in your conclusion: the explorer shows the exact numbers, the rounding step by step and what you got right.
A case has an ID, so you can come back to the same case or send it to a friend.
Try the different kinds: exact cases, classic ones like 0.1 + 0.2, cases where rounding errors cancel (0.1 + 0.3), numbers of very different sizes, and ties.
The explorer needs JavaScript. Without it, here is one case: in binary64, 0.1 + 0.2 is the sum of the stored numbers 0.1000000000000000055511151231257827… and 0.200000000000000011102230246251565…, whose exact sum lies exactly halfway between two stored numbers. Ties to even picks 0.3000000000000000444089209850062616…, which is not the stored 0.3, so the comparison is False.
What to look for
Do not stop at “is there a decimal tail”. In each case ask three things:
which numbers are stored exactly; how many significant bits the exact sum of the stored numbers needs; and, when it needs more than the format keeps, how close it lies to the middle between two stored numbers.
The text printed by a program is only a short name for the stored number, never the real number it looks like.
Workout: store a decimal number, step by step
Each case is a new decimal number and a small floating-point format.
Work out how the number is stored, one step at a time: the exponent, the scaled significand, its rounding, the bits, the stored value and the errors.
Every step is checked against the exact value. Choose “Check at the end” to fill in everything first, and open one to three calculators beside the work.
A case ID brings back the same case.
The workout needs JavaScript. Without it, take 5.3 in a format with a 5-bit significand: 2^2 ≤ 5.3 < 2^3, so e = 2; the scaled number is S = 5.3 · 2^2 = 21.2; M = 21 = 10101 in binary; the stored value is 21/4 = 5.25.
What the limits mean
1. Range is finite. The largest and smallest binary64 numbers are listed in the range of binary64.
Overflow gives infinity, which then spreads through later calculations, and underflow drops small contributions without a warning.
Both are signs to rescale the problem.
2. Do not test computed numbers with ==. Use math.isclose with a comparison tolerance, as in the lecture.
In the code, rel_tol is the relative tolerance and abs_tol the absolute tolerance of the lecture; the default of abs_tol is 0.
Run the snippet. Before you do, predict what you expect to see on each of the four lines, and afterwards explain why the third and the fourth lines differ.
import math
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
print(math.isclose(1e-20, 0.0))
print(math.isclose(1e-20, 0.0, abs_tol=1e-12))
Explanation
rel_tol measures the difference relative to the size of the numbers.
When one number is 0, any positive difference is infinitely large relative to it, so math.isclose(1e-20, 0.0) returns False even though 1e-20 is tiny.
Adding abs_tol=1e-12 allows an absolute difference up to , so the fourth line returns True.
3. A tolerance cannot be smaller than the gap. The rule is in A tolerance cannot be smaller than the gap.
Here it means that a stopping threshold of for a root near 1 is below the gap , so the loop may never end.
A puzzle: when a tie is not a tie
The function round(x, n) rounds x to n digits after the decimal point.
It raises a question when x lies exactly halfway between two candidates, a tie; the lecture explains how round treats a typed decimal.
This puzzle comes from my LinkedIn posts of April 2024, where it started a long discussion.
Work it out: what does this print?
print(1000 * (round(1.2345, 3) - round(1.2335, 3)))
Decide on your answer and the rule you used, then choose an option:
A: 1
The thinking: at school you learn that a half rounds up. By that rule 1.2345 becomes 1.235 and 1.2335 becomes 1.234, the difference is 0.001, and times 1000 gives 1.
The mistakes: Python does not round “half up” here (see the correct answer).
And round of a float returns a float, so even with this reasoning the result would not print as the whole number 1.
B: 1.0
The thinking: the same school rule, half rounds up, this time noticing that the result is a float and so is written 1.0.
The mistakes: Python does not round half up here. And even if it did, 1.235 and 1.234 are not stored exactly, so 1000 * (1.235 - 1.234) gives 1.000000000000112, not exactly 1.0.
C: 0.0
Both calls return 1.234, the difference of two floats is the float 0.0, and 1000 * 0.0 is 0.0.
The tempting explanation is “ties go to the even digit”: 1.2345 goes down to 1.234 (4 is even) and 1.2335 goes up to 1.234 (3 is odd).
It fits here, but it is not what Python does. Test it on round(2.675, 2):
half to even on the typed digits would give 2.68 (7 is odd), but Python returns 2.67.
Python rounds the exact value that is stored. The stored value of 1.2345 is 1.23449999…, just below the midpoint, so it rounds down.
The stored value of 1.2335 is 1.23350000…, just above the midpoint, so it rounds up.
Both land on 1.234.
D: 0
The thinking: the rule “a tie goes to the even digit”. 1.2345 goes down to 1.234 (4 is even) and 1.2335 goes up to 1.234 (3 is odd).
Both round to the same number, so the difference is zero. The answer is right in this case only, and the rule itself is wrong.
The mistakes: round of a float returns a float, so the difference is 0.0, not the whole number 0.
And the rule itself is not what Python does: it does not round the digits you typed but the stored binary value, so here the rule fits only by coincidence.
Hint
Both numbers are ties: 1.2345 is halfway between 1.234 and 1.235, and 1.2335 is halfway between 1.233 and 1.234.
What does the rule “a tie goes to the even last digit” give for each?
Then ask whether the computer really holds the digits you typed, and check with the explorer below.
Use the explorer to see this for any number. The grid below it is the table from the second LinkedIn post:
every row is a tie 0.5, 1.5, …, 9.5 divided by a power of ten, and each cell shows on which side of the tie the stored number falls.
round(x, n) | Stored value of x | Stored value against the midpoint | Python returns |
|---|---|---|---|
round(1.2345, 3) | 1.23449999999999993… | below | 1.234 |
round(1.2335, 3) | 1.23350000000000004… | above | 1.234 |
round(2.675, 2) | 2.67499999999999982… | below | 2.67 |
round(0.125, 2) | 0.125 (exact) | exactly on it: a true tie | 0.12 (even) |
round(2.5) | 2.5 (exact) | exactly on it: a true tie | 2 (even) |
The rows with an exact value are true ties; in the others the stored number falls on one side of the midpoint, as the grid shows.
For lab data this rarely matters. For money it does, and the lecture shows the decimal module for that case, in Rounding a typed decimal.
Common mistakes
Try to find the flaw in each tempting claim before opening its explanation.
“Python has a bug: 0.1 + 0.2 should be exactly 0.3.”
Why this is wrong
The reasoning assumes that the computer stores the decimal digits we typed.
It does not: it stores the nearest binary number. Neither 0.1 nor 0.2 nor 0.3 ends in binary, so each is rounded, and the rounded values of 0.1 and 0.2 add up to a number slightly different from the rounded value of 0.3.
The arithmetic is correct for the stored numbers.
“A double stores 16 decimal digits exactly.”
Why this is wrong
The reasoning treats the format as decimal. The 52 fraction bits give a relative error of at most per rounding.
That is better than the bound of 16 significant decimal digits.
The stored value is a binary number whose exact decimal expansion is much longer than that (see the 55-digit expansion of 0.1 in the answer to the opening question, in the lecture Back to the Question: Rounding and Machine Epsilon).
“A float near is as accurate as a float near 1, in absolute terms.”
Why this is wrong
The reasoning confuses absolute and relative accuracy. The relative accuracy is the same, at most in both places, but the absolute gap is proportional to the size of the number:
near 1 and 2 near .
Transfer practice
- Why does
0.5 + 0.25 == 0.75giveTruewhile0.1 + 0.2 == 0.3givesFalse? - Near the gap between stored numbers is 2. What is the value of
1e16 + 1 == 1e16, and of1e16 + 2 == 1e16? Explain. - Near the gap between neighbouring stored numbers is 2. A real number between two such neighbours is rounded to the nearest one. What is the largest absolute error this rounding can cause?
Solutions
- The numbers , and are all stored exactly and their sum is exactly representable, so no rounding occurs. Each of , and is rounded when stored.
- The first gives
True: the exact sum lies exactly halfway between and , and the tie goes to even, back to . The second givesFalse: is a stored number, so it differs from . - The largest error is half the gap, : a number between two neighbours that are 2 apart is at most 1 away from the nearer one, and a number exactly halfway is 1 away from both. The relative bound times the size, about , is also true, but it is not the largest error.
Implement it yourself
Machine epsilon is defined by a gap, so you can find it by experiment.
Complete the function: halve eps until adding half of it to 1 no longer changes 1.
The program compares your result with Python’s own value. Press Run; if it prints False, find out why before opening the solution.
Python in this task. It asks you to write code, a few lines inside a function that is already written.def defines a function; for _ in range(100) repeats at most 100 times; break leaves the loop; if runs the indented lines below it only when the condition is true; sys.float_info.epsilon is Python’s own value of machine epsilon; abs(x) is the absolute value and max(a, b) the larger of two numbers (used in the second task).
import sys
def machine_epsilon():
eps = 1.0
for _ in range(100):
# TODO: stop (break) when 1.0 + eps / 2 is still equal
# to 1.0; otherwise halve eps
pass
return eps
print(
machine_epsilon(), sys.float_info.epsilon,
machine_epsilon() == sys.float_info.epsilon
)
2.220446049250313e-16 2.220446049250313e-16 True
Solution
Replace the TODO lines by
if 1.0 + eps / 2 == 1.0:
break
eps = eps / 2
The loop stops at the last eps for which is still different from 1, the gap between 1 and the next stored number.
As a further step, use math.ulp(1e16) (the gap from 1e16 to the next stored number) to see that the gap near is 2, and explain with the lecture why a relative precision of is not the same thing as an absolute one.
A second task: a comparison tolerance of your own. Write close(a, b, rel_tol, abs_tol), the rule behind math.isclose:
two numbers are close when their difference is at most the larger of a relative bound and an absolute bound.
The five cases below include the case from What the limits mean, where a purely relative test fails near 0.
Before you run it, say which of the five a purely relative test would get wrong.
def close(a, b, rel_tol=1e-9, abs_tol=0.0):
# TODO: True when |a - b| is at most the larger of rel_tol
# * max(|a|, |b|) and abs_tol
return False
cases = [
("0.1 + 0.2 and 0.3", close(0.1 + 0.2, 0.3), True),
("1e10 and 1e10 + 1", close(1e10, 1e10 + 1), True),
("1e-20 and 0, relative only", close(1e-20, 0.0), False),
(
"1e-20 and 0, with abs_tol=1e-12",
close(1e-20, 0.0, abs_tol=1e-12), True
),
("1 and 1.001", close(1, 1.001), False),
]
for name, got, want in cases:
print("ok " if got == want else "FAIL", name)
ok 0.1 + 0.2 and 0.3
ok 1e10 and 1e10 + 1
ok 1e-20 and 0, relative only
ok 1e-20 and 0, with abs_tol=1e-12
ok 1 and 1.001
Solution
Replace the TODO line by
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
Near 0 the relative bound is tiny, so without abs_tol the numbers and 0 are never close.
The absolute bound repairs that, but a fixed abs_tol would be wrong for numbers of size :
that is why both bounds exist.
Continue learning
The rounding puzzle began as two LinkedIn posts, the puzzle and its discussion, whose comments raised the questions of this unit.
Next: the lecture Small Errors, Big Consequences: The Patriot Clock.