---
title: "Floating-Point Numbers"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 4
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 4 — Floating-Point Numbers

Type `0.1 + 0.2 == 0.3` at Python’s prompt. The answer is `False`. Ask for `0.1 + 0.2`, and Python prints `0.30000000000000004`. Nothing is broken: the computer adds exactly what it was given, but it was never given $0.1$. A memory of $64$ bits cannot hold the infinitely many digits that $0.1$ has in base $2$, so it holds the nearest number it can.

This chapter shows which numbers a computer can store with a fractional part, how far apart they are, how the small errors of each operation build up, and how a program should compare such numbers. Its weekend problem is a real failure in which a tenth of a second, stored a little short, added up to a third of a second.

**You already know.**

A number in scientific notation is written $m \times 10^{e}$ with $1 \le m < 10$, such as $6.02 \times 10^{23}$ (mathematics and physics books, grades 9 and 10). In base $2$ each position is worth twice the one on its right (Book 1, grade 8). The previous chapter showed that a processor keeps whole numbers in a fixed number of bits; here too the number of bits is fixed.

## 4.1 Binary fractions

```python
from fractions import Fraction

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(f"{0.1:.30f}")
print(Fraction(0.1))
print(Fraction(0.1) == Fraction(1, 10))
```

***Listing 4.1.** What is $0.1$, really? code/grade-10/04-floating-point/listings/point_one.py*

```
$ python point_one.py
0.30000000000000004
False
0.100000000000000005551115123126
3602879701896397/36028797018963968
False
```

***Output 4.1.** With thirty decimals, the stored `0.1` shows its error; as an exact fraction, its denominator is a power of two.*

The denominator $36{,}028{,}797{,}018{,}963{,}968$ is $2^{55}$. That is the key: the computer stores numbers whose denominator is a power of two.

**Definition 4.1 (Binary fraction).**

A *binary fraction* is a number written in base $2$ with digits after a binary point: $0.b_1 b_2 b_3 \dots$ stands for $b_1 \cdot \tfrac12 + b_2 \cdot \tfrac14 + b_3 \cdot \tfrac18 + \dots$, each position worth half of the one on its left. A number has a binary fraction with finitely many digits exactly when it is a fraction whose denominator can be a power of two.

For example, $0.375 = \tfrac38 = \tfrac14 + \tfrac18$ is $0.011$ in base $2$. But $\tfrac1{10}$ cannot be written with a power of two as denominator ($10$ has the factor $5$), so its binary digits never end. They are found by *doubling*: multiply by $2$; the whole part ($0$ or $1$) is the next digit; keep the fractional part and repeat.

![The doubling method on 0.1. The fraction 0.2 comes back after four steps, so 0.1 is 0.0\,0011\,0011\,0011… in base 2.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-floating-point/fig-feb409bee1ab.svg)

*The doubling method on $0.1$. The fraction $0.2$ comes back after four steps, so $0.1$ is $0.0\,0011\,0011\,0011\dots$ in base $2$.*

```python
from fractions import Fraction


def binary_fraction(x, n):
    """Return the first n binary digits after the point of x, a Fraction, 0 <= x < 1."""
    digits = ""
    for _ in range(n):
        x = 2 * x
        if x >= 1:
            digits += "1"
            x = x - 1
        else:
            digits += "0"
    return digits


print("0.375 = 0." + binary_fraction(Fraction(3, 8), 8))
print("0.1   = 0." + binary_fraction(Fraction(1, 10), 30))
print("1/3   = 0." + binary_fraction(Fraction(1, 3), 30))
```

***Listing 4.2.** The doubling method, computed exactly with fractions. code/grade-10/04-floating-point/listings/to_binary_fraction.py*

```
$ python to_binary_fraction.py
0.375 = 0.01100000
0.1   = 0.000110011001100110011001100110
1/3   = 0.010101010101010101010101010101
```

***Output 4.2.** $0.375$ ends after three digits; $0.1$ and $\tfrac13$ never end.*

A computer that keeps a fixed number of binary digits must therefore cut $0.1$ somewhere. Whatever it keeps is slightly more or slightly less than $0.1$; the decimal number that we type is not the number it stores.

## 4.2 Sign, exponent and significand

Keeping a fixed number of digits *after the point* would waste them: a distance in kilometres between stars and the size of an atom in metres need digits in very different places. Scientific notation solves this by letting the point float, and computers do the same in base $2$.

**Definition 4.2 (Floating-point number).**

A *floating-point number* is a number written $\pm m \times 2^{e}$, where the *sign* is $+$ or $-$, the *exponent* $e$ is a whole number, and the *significand* $m$ is a [binary fraction](#def-g10-floating-point-binary-fraction) with $1 \le m < 2$ and a fixed number of digits. Each of the three parts is stored in a fixed number of bits.

Python’s `float` is the $64$-bit format of the IEEE 754 standard, used by almost every computer. Its bits are split $1 + 11 + 52$: one bit for the [sign](#def-g10-floating-point-float); eleven bits for the [exponent](#def-g10-floating-point-float), stored with $1023$ added so that it is never negative; and fifty-two bits for the digits of the [significand](#def-g10-floating-point-float) after its point. The digit before the point is always $1$, so it is not stored: the [significand](#def-g10-floating-point-float) has $53$ significant bits.

![The 64 bits of the stored 0.1: sign 0; exponent field 1019, that is e = 1019 - 1023 = -4; fraction bits 1001\,1001 … 1010. The value is 1.1001\,1001…1010 × 2-4 in base 2. The last digits … 1010 instead of … 1001\,1001 show that the digits were rounded up.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-floating-point/fig-abeeeeda65b6.svg)

*The $64$ bits of the stored `0.1`: [sign](#def-g10-floating-point-float) $0$; [exponent](#def-g10-floating-point-float) field $1019$, that is $e = 1019 - 1023 = -4$; fraction bits $1001\,1001 \dots 1010$. The value is $1.1001\,1001\dots1010 \times 2^{-4}$ in base $2$. The last digits $\dots 1010$ instead of $\dots 1001\,1001$ show that the digits were rounded up.*

The module `struct` turns a float into its eight bytes, which the listing below cuts into the three fields.

```python
import struct
import sys


def fields(x):
    """Return the sign, exponent and fraction bits of the 64-bit float x, as strings."""
    (n,) = struct.unpack(">Q", struct.pack(">d", x))
    bits = format(n, "064b")
    return bits[0], bits[1:12], bits[12:]


for x in (1.0, -2.5, 0.1):
    sign, exponent, fraction = fields(x)
    e = int(exponent, 2)
    print(f"{x:5}  sign {sign}  exponent {exponent} = {e} - 1023 = {e - 1023}")
    print(f"       fraction {fraction}")
print(float.hex(0.1))
print(sys.float_info.mant_dig, sys.float_info.max_exp, sys.float_info.max)
```

***Listing 4.3.** The three fields of a 64-bit float. code/grade-10/04-floating-point/listings/float_bits.py*

```
$ python float_bits.py
  1.0  sign 0  exponent 01111111111 = 1023 - 1023 = 0
       fraction 0000000000000000000000000000000000000000000000000000
 -2.5  sign 1  exponent 10000000000 = 1024 - 1023 = 1
       fraction 0100000000000000000000000000000000000000000000000000
  0.1  sign 0  exponent 01111111011 = 1019 - 1023 = -4
       fraction 1001100110011001100110011001100110011001100110011010
0x1.999999999999ap-4
53 1024 1.7976931348623157e+308
```

***Output 4.3.** $1.0$ is $1 \times 2^0$ and $-2.5$ is $-1.01 \times 2^1$ in base $2$. `float.hex` writes the [significand](#def-g10-floating-point-float) in hexadecimal; the last line prints the number of significant bits, the largest [exponent](#def-g10-floating-point-float) and the largest float.*

Sixty-four bits are too many to work by hand. A toy format of $8$ bits has the same structure: one [sign](#def-g10-floating-point-float) bit, $3$ [exponent](#def-g10-floating-point-float) bits $E$ stored with $3$ added, and $4$ fraction bits $F$; a positive pattern stands for $(1 + F/16) \times 2^{E - 3}$. (The toy format has no zero and no [special values](#def-g10-floating-point-special); the real one reserves some patterns for them.)

```python
from fractions import Fraction


def toy_value(e, f):
    """Value of the pattern with exponent field e (0..7), fraction field f (0..15)."""
    return (1 + Fraction(f, 16)) * Fraction(2) ** (e - 3)


values = sorted(toy_value(e, f) for e in range(8) for f in range(16))
print(len(values), "positive values, from", values[0], "to", values[-1])
for e in range(8):
    low = toy_value(e, 0)
    gap = toy_value(e, 1) - low
    high = toy_value(e, 15)
    print(f"exponent field {e}: from {str(low):>4} to {str(high):>6}, gap {gap}")
```

***Listing 4.4.** Every value of the toy format. code/grade-10/04-floating-point/listings/toy_float.py*

```
$ python toy_float.py
128 positive values, from 1/8 to 31
exponent field 0: from  1/8 to 31/128, gap 1/128
exponent field 1: from  1/4 to  31/64, gap 1/64
exponent field 2: from  1/2 to  31/32, gap 1/32
exponent field 3: from    1 to  31/16, gap 1/16
exponent field 4: from    2 to   31/8, gap 1/8
exponent field 5: from    4 to   31/4, gap 1/4
exponent field 6: from    8 to   31/2, gap 1/2
exponent field 7: from   16 to     31, gap 1
```

***Output 4.4.** Sixteen values for each [exponent](#def-g10-floating-point-float), evenly spaced inside the group; the gap doubles from one group to the next.*

![The 128 values of the toy format on a number line. There are as many values between 16 and 31 as between 1/8 and 1/4: floating-point numbers keep the same number of significant digits, not the same number of digits after the point.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-floating-point/fig-811170d25f73.svg)

*The $128$ values of the toy format on a number line. There are as many values between $16$ and $31$ as between $\tfrac18$ and $\tfrac14$: [floating-point numbers](#def-g10-floating-point-float) keep the same number of significant digits, not the same number of digits after the point.*

## 4.3 Gaps between neighbours

The same happens in the 64-bit format. Between $1$ and $2$ the [significands](#def-g10-floating-point-float) $1.00\dots0$ to $1.11\dots1$ give $2^{52}$ values, evenly spaced by $2^{-52}$; between $2$ and $4$, the same number of values spaced by $2^{-51}$; and so on. `math.nextafter(x, math.inf)` gives the next float above `x`, and `math.ulp(x)` the gap.

![Neighbouring floats around 1 and 2, far from scale: the ticks stand for floats. The gap doubles at each power of two.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-floating-point/fig-caf2594f4674.svg)

*Neighbouring floats around $1$ and $2$, far from scale: the ticks stand for floats. The gap doubles at each power of two.*

```python
import math

for x in (1.0, 2.0, 1000.0, 2.0**52, 2.0**53):
    up = math.nextafter(x, math.inf)
    print(f"{x:>18}  next float up {up:>20}  gap {math.ulp(x)}")
print(2.0**53 + 1 == 2.0**53)
print(1.0 + 2.0**-53 == 1.0, 1.0 + 2.0**-52 == 1.0)
```

***Listing 4.5.** Next floats and gaps. code/grade-10/04-floating-point/listings/gaps.py*

```
$ python gaps.py
               1.0  next float up   1.0000000000000002  gap 2.220446049250313e-16
               2.0  next float up   2.0000000000000004  gap 4.440892098500626e-16
            1000.0  next float up   1000.0000000000001  gap 1.1368683772161603e-13
4503599627370496.0  next float up   4503599627370497.0  gap 1.0
9007199254740992.0  next float up   9007199254740994.0  gap 2.0
True
True False
```

***Output 4.5.** From $2^{52}$ on the gap is $1$; from $2^{53}$ on it is $2$, and $2^{53} + 1$ is not a float.*

**Definition 4.3 (Machine epsilon).**

The *machine epsilon* of a floating-point format is the gap between $1$ and the next number of the format. For the 64-bit format it is $2^{-52} \approx 2.2 \times 10^{-16}$.

**Proposition 4.4 (Relative size of the gaps).**

For a 64-bit float $x$ with $2^{e} \le x < 2^{e+1}$, the gap to the next float is $2^{e-52}$, which lies between $\tfrac12 \varepsilon x$ and $\varepsilon x$, where $\varepsilon = 2^{-52}$. All whole numbers from $0$ to $2^{53}$ are floats, but $2^{53} + 1$ is not.

**Proof.** On $[2^e, 2^{e+1})$ the floats are $m \times 2^e$ with $m = 1 + k/2^{52}$ for $k = 0, \dots, 2^{52} - 1$: the gap is $2^{e} \times 2^{-52}$. Since $2^e \le x < 2^{e+1}$, that gap is between $\tfrac12 \varepsilon x$ and $\varepsilon x$. For $e \le 52$ the gap is at most $1$, so every whole number below $2^{53}$ is a float; for $e = 53$ the gap is $2$, so after $2^{53}$ the next float is $2^{53} + 2$. ∎

So a float has about $16$ significant decimal digits, whatever its size. That is plenty for most measurements; the trouble comes when errors build up.

## 4.4 Rounding error and how it builds up

**Definition 4.5 (Rounding error).**

When the exact result of an operation, or a number typed in decimal, is not a float, the computer keeps the nearest float. The difference between the exact value and the stored value is the *rounding error*. For one operation it is at most half the gap, that is, at most $\tfrac12\varepsilon$ times the size of the result.

One [rounding error](#def-g10-floating-point-rounding-error) is tiny. But each addition makes a new one, and a program that adds many numbers adds their errors too.

```python
import math

for count in (10, 1_000_000):
    tenths = [0.1] * count
    total = 0.0
    for t in tenths:
        total = total + t
    print(f"{count} tenths: loop {total!r}  fsum {math.fsum(tenths)!r}")

print(1e16 + 1.0 - 1e16, 1e16 - 1e16 + 1.0)
```

***Listing 4.6.** Adding tenths, by a loop and with `math.fsum`. code/grade-10/04-floating-point/listings/sum_tenths.py*

```
$ python sum_tenths.py
10 tenths: loop 0.9999999999999999  fsum 1.0
1000000 tenths: loop 100000.00000133288  fsum 100000.0
0.0 1.0
```

***Output 4.6.** A million additions lose about $1.3 \times 10^{-6}$. The last line adds the same three numbers in two orders.*

The function `math.fsum` keeps track of the digits lost at each step and rounds only once, at the end; it is slower, and exact enough to give $1.0$ and $100000.0$. The last line shows that the order of the additions matters: $10^{16} + 1$ is not a float (it lies above $2^{53}$, where the gap is $2$), so the $1$ is lost if it is added to $10^{16}$ first, and kept if $10^{16} - 10^{16}$ is computed first. Addition of floats is not associative.

The worst case is the subtraction of two nearly equal numbers. Their leading digits cancel, and what remains is mostly the [rounding error](#def-g10-floating-point-rounding-error) they carried.

```python
import math

x = 1e-8
print("1 - cos(x)        :", 1 - math.cos(x))
print("2 * sin(x / 2)**2 :", 2 * math.sin(x / 2) ** 2)
print("x**2 / 2          :", x**2 / 2)
```

***Listing 4.7.** Three ways to compute $1 - \cos x$ for a small $x$. code/grade-10/04-floating-point/listings/cancel.py*

```
$ python cancel.py
1 - cos(x)        : 0.0
2 * sin(x / 2)**2 : 5.0000000000000005e-17
x**2 / 2          : 5.0000000000000005e-17
```

***Output 4.7.** The direct formula gives $0$: every correct digit was lost.*

For $x = 10^{-8}$, $\cos x$ is so close to $1$ that it rounds to exactly $1.0$, and the subtraction gives $0$. The formula $1 - \cos x = 2\sin^2(x/2)$, from trigonometry, avoids the subtraction and gives the right value, $5 \times 10^{-17}$, very nearly $x^2/2$.

**Method 4.6 (Keeping rounding errors small).**

1. Count with whole numbers when you can: money in cents, time in ticks, and compute the decimal value only to print it.
2. Compute a value directly ( `k * 0.1` ) rather than by adding a step many times.
3. Avoid subtracting nearly equal numbers; look for a formula that does not.
4. To add many numbers, use `math.fsum` .

## 4.5 Comparing floats, and special values

Since computed floats carry [rounding errors](#def-g10-floating-point-rounding-error), `==` between two of them asks the wrong question. The right question is whether they are close.

**Method 4.7 (Comparing two floats).**

Use `math.isclose(a, b)`, which is true when $|a - b| \le 10^{-9} \times \max(|a|, |b|)$: a *relative* tolerance, which scales with the numbers. Near zero a relative tolerance is too strict (only $0$ is close to $0$), so add an *absolute* tolerance chosen from the problem: `math.isclose(a, b, abs_tol=1e-9)`.

The format also reserves some patterns for results that are not ordinary numbers.

**Definition 4.8 (Special values).**

The *special values* of the floating-point format are `inf` and `-inf`, the results of an overflow beyond the largest float; `nan` (“not a number”), the result of an operation that has no meaning, such as $\infty - \infty$; and `-0.0`, a zero that remembers it came from the negative side. Every comparison with `nan` is false, even `nan == nan`.

```python
import math

a = 0.1 + 0.2
print(a == 0.3, math.isclose(a, 0.3))
print(math.isclose(1e-12, 0.0), math.isclose(1e-12, 0.0, abs_tol=1e-9))

big = 1e308 * 10
print(big, -big, big - big)
nan = big - big
print(nan == nan, math.isnan(nan), max(nan, 1.0), max(1.0, nan))
print(0.0 == -0.0, math.copysign(1.0, -0.0))
```

***Listing 4.8.** Closeness and [special values](#def-g10-floating-point-special). code/grade-10/04-floating-point/listings/compare.py*

```
$ python compare.py
False True
False True
inf -inf nan
False True nan 1.0
True -1.0
```

***Output 4.8.** `max` gives a different answer depending on where the `nan` is.*

The fourth line shows why `nan` is dangerous: `max(nan, 1.0)` keeps `nan` because `1.0 > nan` is false, while `max(1.0, nan)` keeps `1.0` for the same reason. A missing measurement stored as `nan` can silently change a result. Test for it with `math.isnan`, never with `==`.

**History — A standard for floating-point arithmetic.**

Before the 1980s, each make of computer had its own floating-point format and its own rounding, and the same program could give different answers on two machines. The IEEE published a common standard, IEEE 754, in 1985; its current edition dates from 2019. Thanks to it, the results of this chapter’s listings are the same on every computer that runs Python.

## 4.6 Exercises

**Exercise 4.1 ★.**

What do `0.1 * 3`, `0.1 * 3 == 0.3`, `0.5 * 3 == 1.5` and `0.25 + 0.5 == 0.75` print? Why are the last two `True`?

**Solution of Exercise 4.1.**

`0.30000000000000004`, `False`, `True`, `True`. The numbers $0.5$, $1.5$, $0.25$ and $0.75$ have a power of two as denominator ($\tfrac12$, $\tfrac32$, $\tfrac14$, $\tfrac34$): they are stored exactly, and so are the exact results of these operations, which are floats too. $0.1$ and $0.3$ are not stored exactly.

**Exercise 4.2 ★.**

Write $0.375$, $0.8125$ and $5.75$ in base $2$, by the doubling method for the fractional parts.

**Solution of Exercise 4.2.**

$0.375$: $0.75 \to 0$, $1.5 \to 1$, $1.0 \to 1$, so $0.011$. $0.8125$: $1.625 \to 1$, $1.25 \to 1$, $0.5 \to 0$, $1.0 \to 1$, so $0.1101$. $5.75 = 101.11$ (the whole part $5$ is $101$, the fraction $0.75$ is $0.11$).

**Exercise 4.3 ★.**

Find the binary digits of $\tfrac13$ by the doubling method, and show that they repeat. What is the period?

**Solution of Exercise 4.3.**

$\tfrac13 \to \tfrac23$, digit $0$; $\tfrac23 \to \tfrac43$, digit $1$, keep $\tfrac13$; and $\tfrac13$ has come back. So $\tfrac13 = 0.010101\dots$ in base $2$, with period $01$, two digits, as the listing printed.

**Exercise 4.4 ★.**

What do `math.isclose(1.0, 1.0 + 1e-10)`, `math.isclose(1e-10, 2e-10)` and `math.isclose(1e-10, 2e-10, abs_tol=1e-9)` return? Explain each with the formula of the method.

**Solution of Exercise 4.4.**

`True`: $10^{-10} \le 10^{-9} \times 1$. `False`: $|a - b| = 10^{-10}$ but $10^{-9} \times 2 \times 10^{-10}$ is far smaller; relatively, $10^{-10}$ and $2 \times 10^{-10}$ differ by a factor of two. `True`: the absolute tolerance $10^{-9}$ is larger than $10^{-10}$.

**Exercise 4.5 ★.**

The loop `x = 0.0` then `while x != 1.0: x = x + 0.1` never stops. Using the output on adding tenths, say why, and rewrite the loop so that it stops after ten turns.

**Solution of Exercise 4.5.**

After ten additions `x` is `0.9999999999999999`, not `1.0`, so `x != 1.0` stays true and the loop goes on for ever. Count whole turns instead: `for k in range(1, 11): x = k * 0.1`, or test `while x < 0.95`, a bound far from any [rounding error](#def-g10-floating-point-rounding-error).

**Exercise 4.6 ★★.**

A 64-bit float has the [sign](#def-g10-floating-point-float) bit $1$, the [exponent](#def-g10-floating-point-float) field `10000000010` and the fraction bits `1100` followed by $48$ zeros. What number is it?

**Solution of Exercise 4.6.**

The [sign](#def-g10-floating-point-float) is $-$; the [exponent](#def-g10-floating-point-float) field is $1024 + 2 = 1026$, so $e = 1026 - 1023 = 3$; the [significand](#def-g10-floating-point-float) is $1.11$ in base $2$, that is $1.75$. The number is $-1.75 \times 2^3 = -14$.

**Exercise 4.7 ★★.**

Every float is a fraction with a power of two as denominator, so its binary digits end. Write `exact_binary(x)`, which returns all the binary digits after the point of a float $0 \le x < 1$, using `Fraction(x)` and the doubling method. How many digits does the stored `0.1` have?

**Solution of Exercise 4.7.**

In `exercises/exact_binary.py`: `q = Fraction(x)`, then, while `q != 0`, double `q`, write the digit `1` and subtract $1$ if `q >= 1`, else write `0`. The loop ends because each doubling removes a factor $2$ from the denominator. The stored `0.1` is $3602879701896397/2^{55}$: its binary digits stop at the $55$th place.

**Exercise 4.8 ★★.**

What is the gap between $2^{20}$ and the next float? How many floats are there between $2^{20}$ and $2^{21}$? Check with `math.ulp`.

**Solution of Exercise 4.8.**

$2^{20}$ lies in $[2^{20}, 2^{21})$, where the gap is $2^{20-52} = 2^{-32} \approx 2.33 \times 10^{-10}$, which is what `math.ulp(2.0**20)` prints. There are $2^{52}$ floats in $[2^{20}, 2^{21})$, as in every interval between two consecutive powers of two.

**Exercise 4.9 ★★.**

What do `(1e16 + 1.0) + 1.0`, `1e16 + (1.0 + 1.0)` and `sum([1e16, 1.0, 1.0])` print? Which order of addition keeps the most digits?

**Solution of Exercise 4.9.**

The first line prints `1e+16`: each `1.0` is lost in turn, since $10^{16} + 1$ is not a float and rounds back to $10^{16}$. `1.0000000000000002e+16`: $1 + 1 = 2$ is computed first, and $10^{16} + 2$ is a float. `sum` also prints `1.0000000000000002e+16`: since Python 3.12 it keeps the lost digits along the way, like `math.fsum` (an older Python’s `sum` prints `1e+16`). Adding the small numbers together first keeps the most digits.

**Exercise 4.10 ★★.**

A timer fires every $0.1$ s, and a program computes the time of the $k$th firing either with `t += 0.1` or as `k * 0.1`. For the first $30$ firings, which method gives `k / 10` exactly more often? Explain with the method of this chapter.

**Solution of Exercise 4.10.**

`k * 0.1` matches `k / 10` for $19$ of the $30$ firings, `t += 0.1` for only $8$ (`exercises/accumulate.py`). The product makes one [rounding error](#def-g10-floating-point-rounding-error); the sum carries every error of the additions before it. That is the second item of the method on keeping [rounding errors](#def-g10-floating-point-rounding-error) small.

**Exercise 4.11 ★★.**

Write `almost_equal(a, b, rel, abs_)` that combines a relative and an absolute tolerance as `math.isclose` does, and test it against `math.isclose` on random pairs.

**Solution of Exercise 4.11.**

`return abs(a - b) <= max(rel * max(abs(a), abs(b)), abs_)`, with `rel=1e-9` and `abs_=0.0` by default (`exercises/almost_equal.py`); the chapter’s tests compare it with `math.isclose` on $500$ random pairs.

**Exercise 4.12 ★★★.**

Prove that $2^{53} + 1$ is not a 64-bit float, and that $2^{53} + 2$ is. What does `2**53 + 1.0` give?

**Solution of Exercise 4.12.**

$2^{53} + 1$ lies in $[2^{53}, 2^{54})$, where the floats are $m \times 2^{53}$ with $m$ having $52$ binary digits after the point: they are $2^{53} + 2k$ for whole numbers $k$, all even. $2^{53} + 1$ is odd, so it is not one of them; $2^{53} + 2$ is ($k = 1$). `2**53 + 1.0` gives `9007199254740992.0`: the exact sum is exactly halfway between two floats, and the rule rounds to the one whose last bit is $0$, here $2^{53}$.

**Exercise 4.13 ★★★.**

In the toy format, how many values lie in $[1, 2)$, in $[2, 4)$, and in all? Which whole numbers from $1$ to $31$ are values of the format? Which is the smallest whole number that is not?

**Solution of Exercise 4.13.**

$16$ values in $[1, 2)$ ([exponent](#def-g10-floating-point-float) field $3$), $16$ in $[2, 4)$, and $8 \times 16 = 128$ positive values in all, as the listing printed. Every whole number from $1$ to $31$ is a value: from $1$ to $15$ the gaps are at most $\tfrac12$, and from $16$ to $31$ the gap is exactly $1$. The smallest whole number that is not a value is $32$, above the largest value, $31$.

**Exercise 4.14 ★★★.**

The roots of $x^2 + bx + c$, for $b > 0$ large and $c = 1$, are found with the formula $\left(-b \pm \sqrt{b^2 - 4c}\right)/2$. For $b = 10^8$, compute the small root with the $+$ [sign](#def-g10-floating-point-float), then as $c$ divided by the large root (the product of the roots is $c$). Explain the difference, and say which is right.

**Solution of Exercise 4.14.**

With the $+$ [sign](#def-g10-floating-point-float), $\sqrt{b^2 - 4}$ is extremely close to $b = 10^8$, and the subtraction $-b + \sqrt{b^2 - 4}$ loses nearly every digit: Python gives $-7.450580596923828 \times 10^{-9}$. The large root is about $-10^8$, computed with an addition of two negative numbers and no cancellation; $c$ divided by it gives $-10^{-8}$, which is right to all printed digits, since the small root is $-10^{-8} - 10^{-24} - \dots$ (`exercises/quadratic.py`). The second method is right; the first is wrong by $25\,\%$.

**Exercise 4.15 ★★★.**

A weather station’s readings are floats, and a missing reading is stored as `nan`. The function `largest` starts with `best = readings[0]` and keeps any `r > best`. What does it return for `[nan, 3.0, 7.0]`, and for `[3.0, nan, 7.0]`? Correct it.

**Solution of Exercise 4.15.**

For `[nan, 3.0, 7.0]` it returns `nan`: `best` starts as `nan`, and `r > nan` is always false. For `[3.0, nan, 7.0]` it returns `7.0`, since `nan > 3.0` is false and `nan` is skipped. The fix removes the missing readings first, `values = [r for r in readings if not math.isnan(r)]`, asserts that some remain, and takes the largest of them (`exercises/nan_max.py`).

## 4.7 Problem: A Clock That Drifts

**Problem 4.1.**

Weekend problem — a third of a second in a hundred hours

On 25 February 1991, an air-defence system at Dhahran, in Saudi Arabia, failed to intercept an incoming missile, which hit a barracks and killed $28$ soldiers. A report of the U.S. General Accounting Office found the cause: the system counted time in tenths of a second as a whole number, and converted it to seconds with registers only $24$ bits long; the conversion lost precision, and the error grew the longer the system ran. The battery had been running for about $100$ hours. The report’s table gives the error: $0.0275$ s after $8$ hours, $0.3433$ s after $100$ hours, and a shift of $687$ m in where the system looked for its target. This problem rebuilds the table; the program `exercises/clock_drift.py` does the exact arithmetic.

**Part I — A tenth, chopped.**

1. Using the figure on the doubling method, write the first $27$ binary digits of $0.1$ after the point.
2. A value is *chopped* after $p$ binary places when the digits after the $p$ th are dropped. Write the function `chopped(x, bits)` of the program in words.
3. Show that the digits of $0.1$ dropped after the $23$ rd place are $0.11001100\dots$ times $2^{-23}$ , that is $0.8 \times 2^{-23}$ .
4. Deduce the error of one tenth chopped after $23$ places, and give it in seconds to three significant digits.

**Part II — The error per tick.**

5. The clock adds the chopped tenth at each tick. How many ticks are there in one hour?
6. Compute the drift after one hour, and compare it with the report’s $0.0034$ s.
7. In the same way, compute the drift after $8$ hours and compare it with $0.0275$ s.
8. Why does the drift grow in proportion to the running time?

**Part III — A hundred hours.**

9. How many ticks are there in $100$ hours?
10. Compute the drift after $100$ hours from the error per tick.
11. Run the program and compare its six lines with the report’s values at $1$ , $8$ , $20$ , $48$ , $72$ and $100$ hours.
12. The program also computes the drift for a tenth chopped after $24$ places. What is it after $100$ hours? Which of the two matches the report?
13. Rebooting the system resets the count of ticks to $0$ . What drift would remain if it were rebooted every $8$ hours?

**Part IV — From time to distance.**

14. An error in time becomes an error in position: an object moving at $v$ metres per second covers $v \times t$ metres in $t$ seconds. From the report’s $0.3433$ s and $687$ m, find the speed it assumed, to the nearest $10$ m/s.
15. With that speed, check the report’s shift of $55$ m after $8$ hours.
16. How far would the target have moved during the drift after $100$ hours with the $24$ -place tenth?
17. The error could have been avoided by counting time only in whole ticks. Explain how, using the method on keeping [rounding errors](#def-g10-floating-point-rounding-error) small.
18. Suppose instead that the time is computed as the number of ticks times a 64-bit `0.1` , whose [rounding error](#def-g10-floating-point-rounding-error) is about $5.6 \times 10^{-18}$ , with one more rounding for the product. Estimate the error after $100$ hours. Is it zero?
19. State the result: the error of one tick, and the drift after $100$ hours, computed exactly, compared with the report.

**Solution of Problem 4.1.**

**1.** $0.000110011001100110011001100$ (the digits $0011$ repeat from the second place on).

**2.** Multiply $x$ by $2^{p}$, drop the fractional part, and divide by $2^{p}$ again: what remains is $x$ with only its first $p$ binary places.

**3.** The digits from the second place on repeat $0011$; the $24$th and $25$th digits are $1$ and $1$, then $0011$ again. So the dropped part is $0.11001100\dots \times 2^{-23}$, and $0.1100\,1100\dots$ in base $2$ is $2 \times 0.0110\,0110\dots = 2 \times 0.4 = 0.8$ (since $0.4$ is $0.1$ doubled twice, $0.0110\,0110\dots$).

**4.** $0.8 \times 2^{-23} \approx 9.54 \times 10^{-8}$ s per tick, as the program prints.

**5.** $3600 \times 10 = 36{,}000$ ticks.

**6.** $36{,}000 \times 9.537 \times 10^{-8} \approx 0.0034$ s, the report’s value.

**7.** $8 \times 36{,}000 = 288{,}000$ ticks, so $288{,}000 \times 9.537 \times 10^{-8} \approx 0.0275$ s, again the report’s value.

**8.** Each tick adds the same error, so the total error is the number of ticks times the error per tick, and the number of ticks grows in proportion to the time.

**9.** $100 \times 36{,}000 = 3{,}600{,}000$ ticks.

**10.** $3{,}600{,}000 \times 0.8 \times 2^{-23} \approx 0.3433$ s.

**11.** The program prints $0.0034$, $0.0275$, $0.0687$, $0.1648$, $0.2472$ and $0.3433$ s: the six values of the report’s table, to the four printed decimals (the chapter’s tests check them).

**12.** $0.1287$ s. Only the tenth chopped after $23$ places matches the report’s figures. The report says that the registers were $24$ bits long, but not how those bits were used; the figures are what point to $23$ places.

**13.** The count restarts at each reboot, so the drift never exceeds its value after $8$ hours, $0.0275$ s.

**14.** $687 / 0.3433 \approx 2001$, so about $2000$ m/s.

**15.** $2000 \times 0.0275 = 55$ m, the report’s shift.

**16.** $2000 \times 0.1287 \approx 257$ m: smaller, but still far more than the size of a target.

**17.** Keep the count of ticks as a whole number, which is exact, and convert it to seconds only when needed with one multiplication or, better, one division by $10$. The error is then a single rounding, whatever the running time: items 1 and 2 of the method.

**18.** The [rounding error](#def-g10-floating-point-rounding-error) of `0.1` contributes $3{,}600{,}000 \times 5.6 \times 10^{-18} \approx 2 \times
10^{-11}$ s, and the rounding of the product, near $360{,}000$, at most half a gap, about $3 \times 10^{-11}$ s. The error is not zero, but about $5 \times 10^{-11}$ s, a billionth of the error of the chopped $23$-place tenth.

**19.** One tick of $0.1$ s chopped after $23$ binary places is short by $0.8 \times 2^{-23} \approx 9.54 \times
10^{-8}$ s; after $100$ hours, that is $3{,}600{,}000$ ticks, the clock is behind by $0.3433$ s, exactly the value published in the report.
