计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本:English。

High School Computer Science · 10–12 年级

4Floating-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.10.1. A memory of 6464 bits cannot hold the infinitely many digits that 0.10.1 has in base 22, 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×10em \times 10^{e} with 1≤m<101 \le m < 10, such as 6.02×10236.02 \times 10^{23} (mathematics and physics books, grades 9 and 10). In base 22 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

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.10.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,96836{,}028{,}797{,}018{,}963{,}968 is 2552^{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 22 with digits after a binary point: 0.b1b2b3…0.b_1 b_2 b_3 \dots stands for b1⋅12+b2⋅14+b3⋅18+…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=38=14+180.375 = \tfrac38 = \tfrac14 + \tfrac18 is 0.0110.011 in base 22. But 110\tfrac1{10} cannot be written with a power of two as denominator (1010 has the factor 55), so its binary digits never end. They are found by doubling: multiply by 22; the whole part (00 or 11) 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.
The doubling method on 0.10.1. The fraction 0.20.2 comes back after four steps, so 0.10.1 is 0.0 0011 0011 0011…0.0\,0011\,0011\,0011\dots in base 22.
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.3750.375 ends after three digits; 0.10.1 and 13\tfrac13 never end.

A computer that keeps a fixed number of binary digits must therefore cut 0.10.1 somewhere. Whatever it keeps is slightly more or slightly less than 0.10.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 22.

Definition 4.2 (Floating-point number)

A floating-point number is a number written ±m×2e\pm m \times 2^{e}, where the sign is ++ or −-, the exponent ee is a whole number, and the significand mm is a binary fraction with 1≤m<21 \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 6464-bit format of the IEEE 754 standard, used by almost every computer. Its bits are split 1+11+521 + 11 + 52: one bit for the sign; eleven bits for the exponent, stored with 10231023 added so that it is never negative; and fifty-two bits for the digits of the significand after its point. The digit before the point is always 11, so it is not stored: the significand has 5353 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.
The 6464 bits of the stored 0.1: sign 00; exponent field 10191019, that is e=1019−1023=−4e = 1019 - 1023 = -4; fraction bits 1001 1001…10101001\,1001 \dots 1010. The value is 1.1001 1001…1010×2−41.1001\,1001\dots1010 \times 2^{-4} in base 22. The last digits …1010\dots 1010 instead of …1001 1001\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.

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.01.0 is 1×201 \times 2^0 and −2.5-2.5 is −1.01×21-1.01 \times 2^1 in base 22. float.hex writes the significand in hexadecimal; the last line prints the number of significant bits, the largest exponent and the largest float.

Sixty-four bits are too many to work by hand. A toy format of 88 bits has the same structure: one sign bit, 33 exponent bits EE stored with 33 added, and 44 fraction bits FF; a positive pattern stands for (1+F/16)×2E−3(1 + F/16) \times 2^{E - 3}. (The toy format has no zero and no special values; the real one reserves some patterns for them.)

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, 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.
The 128128 values of the toy format on a number line. There are as many values between 1616 and 3131 as between 18\tfrac18 and 14\tfrac14: floating-point numbers 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 11 and 22 the significands 1.00…01.00\dots0 to 1.11…11.11\dots1 give 2522^{52} values, evenly spaced by 2−522^{-52}; between 22 and 44, the same number of values spaced by 2−512^{-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.
Neighbouring floats around 11 and 22, far from scale: the ticks stand for floats. The gap doubles at each power of two.
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 2522^{52} on the gap is 11; from 2532^{53} on it is 22, and 253+12^{53} + 1 is not a float.

Definition 4.3 (Machine epsilon)

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

Proposition 4.4 (Relative size of the gaps)

For a 64-bit float xx with 2e≤x<2e+12^{e} \le x < 2^{e+1}, the gap to the next float is 2e−522^{e-52}, which lies between 12εx\tfrac12 \varepsilon x and εx\varepsilon x, where ε=2−52\varepsilon = 2^{-52}. All whole numbers from 00 to 2532^{53} are floats, but 253+12^{53} + 1 is not.

Proof. On [2e,2e+1)[2^e, 2^{e+1}) the floats are m×2em \times 2^e with m=1+k/252m = 1 + k/2^{52} for k=0,…,252−1k = 0, \dots, 2^{52} - 1: the gap is 2e×2−522^{e} \times 2^{-52}. Since 2e≤x<2e+12^e \le x < 2^{e+1}, that gap is between 12εx\tfrac12 \varepsilon x and εx\varepsilon x. For e≤52e \le 52 the gap is at most 11, so every whole number below 2532^{53} is a float; for e=53e = 53 the gap is 22, so after 2532^{53} the next float is 253+22^{53} + 2. ∎

So a float has about 1616 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 12ε\tfrac12\varepsilon times the size of the result.

One rounding error is tiny. But each addition makes a new one, and a program that adds many numbers adds their errors too.

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×10−61.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.01.0 and 100000.0100000.0. The last line shows that the order of the additions matters: 1016+110^{16} + 1 is not a float (it lies above 2532^{53}, where the gap is 22), so the 11 is lost if it is added to 101610^{16} first, and kept if 1016−101610^{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 they carried.

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⁡x1 - \cos x for a small xx. 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 00: every correct digit was lost.

For x=10−8x = 10^{-8}, cos⁡x\cos x is so close to 11 that it rounds to exactly 1.01.0, and the subtraction gives 00. The formula 1−cos⁡x=2sin⁡2(x/2)1 - \cos x = 2\sin^2(x/2), from trigonometry, avoids the subtraction and gives the right value, 5×10−175 \times 10^{-17}, very nearly x2/2x^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, == 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∣≤10−9×max⁡(∣a∣,∣b∣)|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 00 is close to 00), 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.

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. 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

Solution of Exercise 4.1.

0.30000000000000004, False, True, True. The numbers 0.50.5, 1.51.5, 0.250.25 and 0.750.75 have a power of two as denominator (12\tfrac12, 32\tfrac32, 14\tfrac14, 34\tfrac34): they are stored exactly, and so are the exact results of these operations, which are floats too. 0.10.1 and 0.30.3 are not stored exactly.

Exercise 4.2 ★

Write 0.3750.375, 0.81250.8125 and 5.755.75 in base 22, by the doubling method for the fractional parts.

Solution

Solution of Exercise 4.2.

0.3750.375: 0.75→00.75 \to 0, 1.5→11.5 \to 1, 1.0→11.0 \to 1, so 0.0110.011. 0.81250.8125: 1.625→11.625 \to 1, 1.25→11.25 \to 1, 0.5→00.5 \to 0, 1.0→11.0 \to 1, so 0.11010.1101. 5.75=101.115.75 = 101.11 (the whole part 55 is 101101, the fraction 0.750.75 is 0.110.11).

Exercise 4.3 ★

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

Solution

Solution of Exercise 4.3.

13→23\tfrac13 \to \tfrac23, digit 00; 23→43\tfrac23 \to \tfrac43, digit 11, keep 13\tfrac13; and 13\tfrac13 has come back. So 13=0.010101…\tfrac13 = 0.010101\dots in base 22, with period 0101, 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

Solution of Exercise 4.4.

True: 10−10≤10−9×110^{-10} \le 10^{-9} \times 1. False: ∣a−b∣=10−10|a - b| = 10^{-10} but 10−9×2×10−1010^{-9} \times 2 \times 10^{-10} is far smaller; relatively, 10−1010^{-10} and 2×10−102 \times 10^{-10} differ by a factor of two. True: the absolute tolerance 10−910^{-9} is larger than 10−1010^{-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

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.

Exercise 4.6 ★★

A 64-bit float has the sign bit 11, the exponent field 10000000010 and the fraction bits 1100 followed by 4848 zeros. What number is it?

Solution

Solution of Exercise 4.6.

The sign is −-; the exponent field is 1024+2=10261024 + 2 = 1026, so e=1026−1023=3e = 1026 - 1023 = 3; the significand is 1.111.11 in base 22, that is 1.751.75. The number is −1.75×23=−14-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≤x<10 \le x < 1, using Fraction(x) and the doubling method. How many digits does the stored 0.1 have?

Solution

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 11 if q >= 1, else write 0. The loop ends because each doubling removes a factor 22 from the denominator. The stored 0.1 is 3602879701896397/2553602879701896397/2^{55}: its binary digits stop at the 5555th place.

Exercise 4.8 ★★

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

Solution

Solution of Exercise 4.8.

2202^{20} lies in [220,221)[2^{20}, 2^{21}), where the gap is 220−52=2−32≈2.33×10−102^{20-52} = 2^{-32} \approx 2.33 \times 10^{-10}, which is what math.ulp(2.0**20) prints. There are 2522^{52} floats in [220,221)[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

Solution of Exercise 4.9.

The first line prints 1e+16: each 1.0 is lost in turn, since 1016+110^{16} + 1 is not a float and rounds back to 101610^{16}. 1.0000000000000002e+16: 1+1=21 + 1 = 2 is computed first, and 1016+210^{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.10.1 s, and a program computes the time of the kkth firing either with t += 0.1 or as k * 0.1. For the first 3030 firings, which method gives k / 10 exactly more often? Explain with the method of this chapter.

Solution

Solution of Exercise 4.10.

k * 0.1 matches k / 10 for 1919 of the 3030 firings, t += 0.1 for only 88 (exercises/accumulate.py). The product makes one rounding error; the sum carries every error of the additions before it. That is the second item of the method on keeping rounding errors 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

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 500500 random pairs.

Exercise 4.12 ★★★

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

Solution

Solution of Exercise 4.12.

253+12^{53} + 1 lies in [253,254)[2^{53}, 2^{54}), where the floats are m×253m \times 2^{53} with mm having 5252 binary digits after the point: they are 253+2k2^{53} + 2k for whole numbers kk, all even. 253+12^{53} + 1 is odd, so it is not one of them; 253+22^{53} + 2 is (k=1k = 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 00, here 2532^{53}.

Exercise 4.13 ★★★

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

Solution

Solution of Exercise 4.13.

1616 values in [1,2)[1, 2) (exponent field 33), 1616 in [2,4)[2, 4), and 8×16=1288 \times 16 = 128 positive values in all, as the listing printed. Every whole number from 11 to 3131 is a value: from 11 to 1515 the gaps are at most 12\tfrac12, and from 1616 to 3131 the gap is exactly 11. The smallest whole number that is not a value is 3232, above the largest value, 3131.

Exercise 4.14 ★★★

The roots of x2+bx+cx^2 + bx + c, for b>0b > 0 large and c=1c = 1, are found with the formula (−b±b2−4c)/2\left(-b \pm \sqrt{b^2 - 4c}\right)/2. For b=108b = 10^8, compute the small root with the ++ sign, then as cc divided by the large root (the product of the roots is cc). Explain the difference, and say which is right.

Solution

Solution of Exercise 4.14.

With the ++ sign, b2−4\sqrt{b^2 - 4} is extremely close to b=108b = 10^8, and the subtraction −b+b2−4-b + \sqrt{b^2 - 4} loses nearly every digit: Python gives −7.450580596923828×10−9-7.450580596923828 \times 10^{-9}. The large root is about −108-10^8, computed with an addition of two negative numbers and no cancellation; cc divided by it gives −10−8-10^{-8}, which is right to all printed digits, since the small root is −10−8−10−24−…-10^{-8} - 10^{-24} - \dots (exercises/quadratic.py). The second method is right; the first is wrong by 25 %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

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 2828 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 2424 bits long; the conversion lost precision, and the error grew the longer the system ran. The battery had been running for about 100100 hours. The report’s table gives the error: 0.02750.0275 s after 88 hours, 0.34330.3433 s after 100100 hours, and a shift of 687687 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 2727 binary digits of 0.10.1 after the point.
  2. A value is chopped after pp binary places when the digits after the ppth are dropped. Write the function chopped(x, bits) of the program in words.
  3. Show that the digits of 0.10.1 dropped after the 2323rd place are 0.11001100…0.11001100\dots times 2−232^{-23}, that is 0.8×2−230.8 \times 2^{-23}.
  4. Deduce the error of one tenth chopped after 2323 places, and give it in seconds to three significant digits.

Part II — The error per tick.

  1. The clock adds the chopped tenth at each tick. How many ticks are there in one hour?
  2. Compute the drift after one hour, and compare it with the report’s 0.00340.0034 s.
  3. In the same way, compute the drift after 88 hours and compare it with 0.02750.0275 s.
  4. Why does the drift grow in proportion to the running time?

Part III — A hundred hours.

  1. How many ticks are there in 100100 hours?
  2. Compute the drift after 100100 hours from the error per tick.
  3. Run the program and compare its six lines with the report’s values at 11, 88, 2020, 4848, 7272 and 100100 hours.
  4. The program also computes the drift for a tenth chopped after 2424 places. What is it after 100100 hours? Which of the two matches the report?
  5. Rebooting the system resets the count of ticks to 00. What drift would remain if it were rebooted every 88 hours?

Part IV — From time to distance.

  1. An error in time becomes an error in position: an object moving at vv metres per second covers v×tv \times t metres in tt seconds. From the report’s 0.34330.3433 s and 687687 m, find the speed it assumed, to the nearest 1010 m/s.
  2. With that speed, check the report’s shift of 5555 m after 88 hours.
  3. How far would the target have moved during the drift after 100100 hours with the 2424-place tenth?
  4. The error could have been avoided by counting time only in whole ticks. Explain how, using the method on keeping rounding errors small.
  5. Suppose instead that the time is computed as the number of ticks times a 64-bit 0.1, whose rounding error is about 5.6×10−185.6 \times 10^{-18}, with one more rounding for the product. Estimate the error after 100100 hours. Is it zero?
  6. State the result: the error of one tick, and the drift after 100100 hours, computed exactly, compared with the report.
Solution

Solution of Problem 4.1.

1. 0.0001100110011001100110011000.000110011001100110011001100 (the digits 00110011 repeat from the second place on).

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

3. The digits from the second place on repeat 00110011; the 2424th and 2525th digits are 11 and 11, then 00110011 again. So the dropped part is 0.11001100⋯×2−230.11001100\dots \times 2^{-23}, and 0.1100 1100…0.1100\,1100\dots in base 22 is 2×0.0110 0110⋯=2×0.4=0.82 \times 0.0110\,0110\dots = 2 \times 0.4 = 0.8 (since 0.40.4 is 0.10.1 doubled twice, 0.0110 0110…0.0110\,0110\dots).

4. 0.8×2−23≈9.54×10−80.8 \times 2^{-23} \approx 9.54 \times 10^{-8} s per tick, as the program prints.

5. 3600×10=36,0003600 \times 10 = 36{,}000 ticks.

6. 36,000×9.537×10−8≈0.003436{,}000 \times 9.537 \times 10^{-8} \approx 0.0034 s, the report’s value.

7. 8×36,000=288,0008 \times 36{,}000 = 288{,}000 ticks, so 288,000×9.537×10−8≈0.0275288{,}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×36,000=3,600,000100 \times 36{,}000 = 3{,}600{,}000 ticks.

10. 3,600,000×0.8×2−23≈0.34333{,}600{,}000 \times 0.8 \times 2^{-23} \approx 0.3433 s.

11. The program prints 0.00340.0034, 0.02750.0275, 0.06870.0687, 0.16480.1648, 0.24720.2472 and 0.34330.3433 s: the six values of the report’s table, to the four printed decimals (the chapter’s tests check them).

12. 0.12870.1287 s. Only the tenth chopped after 2323 places matches the report’s figures. The report says that the registers were 2424 bits long, but not how those bits were used; the figures are what point to 2323 places.

13. The count restarts at each reboot, so the drift never exceeds its value after 88 hours, 0.02750.0275 s.

14. 687/0.3433≈2001687 / 0.3433 \approx 2001, so about 20002000 m/s.

15. 2000×0.0275=552000 \times 0.0275 = 55 m, the report’s shift.

16. 2000×0.1287≈2572000 \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 1010. The error is then a single rounding, whatever the running time: items 1 and 2 of the method.

18. The rounding error of 0.1 contributes 3,600,000×5.6×10−18≈2×10−113{,}600{,}000 \times 5.6 \times 10^{-18} \approx 2 \times 10^{-11} s, and the rounding of the product, near 360,000360{,}000, at most half a gap, about 3×10−113 \times 10^{-11} s. The error is not zero, but about 5×10−115 \times 10^{-11} s, a billionth of the error of the chopped 2323-place tenth.

19. One tick of 0.10.1 s chopped after 2323 binary places is short by 0.8×2−23≈9.54×10−80.8 \times 2^{-23} \approx 9.54 \times 10^{-8} s; after 100100 hours, that is 3,600,0003{,}600{,}000 ticks, the clock is behind by 0.34330.3433 s, exactly the value published in the report.

本章定义的术语

在术语表中查看全部 1050 个术语