Application and depth

Choosing numbers for real systems

Three real failures (a stock index, a rocket, an aircraft power system) and the design decisions about numbers behind them: representation, rounding rule, range, error threshold and what to do with exceptions.

Last updated:


This page shows how the ideas of the unit decide real engineering outcomes:
three cases where a decision about numbers determined whether the system worked.

Each case starts from something that happened, and then asks you to make the design decisions that were missed.
Five decisions come up every time:

  1. Representation: a whole number, a decimal number or a binary floating-point number, and how many bits.
  2. Rounding rule: truncate, round to nearest, or round to even, and at which step of the computation.
  3. Range: the smallest and largest values the quantity can take, with a safety margin.
  4. Error threshold: how large an error the application can tolerate, absolute or relative.
  5. Exceptions: what the system does when a value is out of range or invalid, and who is told.

Case 1: a stock index that lost half its value

What happened. The Vancouver Stock Exchange index was started at 1000 in January 1982.
At every recalculation its value was truncated to three decimal places instead of rounded.
For a positive value, truncation always moves it down, so the errors do not cancel:
they add up. On Friday 25 November 1983 the index closed at 524.811; after it was recalculated over the weekend with rounding, it stood at 1098.892.
These figures come from secondary sources (see the list at the end), and we did not check the exchange’s own records.

Why the rule matters. Rounding to the nearest thousandth makes the error of each update positive or negative with equal chance, so errors partly cancel.
If the dropped part is spread evenly, truncation loses on average half a thousandth, 0.00050.0005⁠‏, at every update, always in the same direction.

A simulation. The program below is a simulation, not the exchange’s data:
a hypothetical example that shows the direction and scale of the effect.
The index is kept as a whole number of thousandths (a good representation: no binary fractions), and receives small random changes.
In the code, random.Random(seed) makes a random-number generator that starts from a fixed seed (so every run gives the same numbers), rng.uniform(a, b) draws a random number between a and b, and int(...) drops the fraction, which for a positive number is truncation.
Run it, then fix the TODO line so that rounded is rounded and not truncated.

import random

def simulate(n, seed=1):
    """An index that starts at 1000.000 and is updated n times
    by a small random change."""
    rng = random.Random(seed)
    # the value without any rounding
    exact = 1000.0
    # the index in thousandths, as a whole number
    truncated = 1_000_000
    rounded = 1_000_000
    for _ in range(n):
        r = rng.uniform(-0.0004, 0.0004)
        exact *= 1 + r
        truncated = int(truncated * (1 + r))
        # TODO: round to the nearest thousandth instead of
        # truncating
        rounded = int(rounded * (1 + r))
    return exact, truncated / 1000, rounded / 1000

for n in (1000, 20000, 200000):
    e, t, r = simulate(n)
    print(
        f"{n:>7} updates: exact {e:9.3f}   "
        f"truncated {t:9.3f} (off by {t - e:8.3f})   "
        f"rounded {r:9.3f} (off by {r - e:7.3f})"
    )
   1000 updates: exact  1011.347   truncated  1010.851 (off by   -0.496)   rounded  1011.349 (off by   0.002)
  20000 updates: exact   996.965   truncated   986.918 (off by  -10.047)   rounded   996.904 (off by  -0.061)
 200000 updates: exact  1074.512   truncated   970.184 (off by -104.328)   rounded  1074.306 (off by  -0.206)
Solution

Replace the TODO line by this line:

rounded = round(rounded * (1 + r))

The truncated index loses about 0.00050.0005 per update, in the same direction:
0.50.5 after 1,000 updates, about 1010 after 20,000 and about 100100 after 200,000, in proportion to the number of updates.
The rounded index stays within a fraction of a point of the exact value, because its errors cancel.

Questions.

  1. Which of the five decisions was wrong, and what is the smallest change to the program that repairs it?
  2. The truncation error after nn updates is about 0.0005 n0.0005\,n⁠‏. After how many updates would it reach 100 points? Check against the output.
  3. Why is a whole number of thousandths a better representation of the index than a binary float?
Solutions
  1. The rounding rule (decision 2). Replace truncation by rounding to the nearest thousandth at each update; nothing else has to change.
  2. 1000.0005=200,000\frac{100}{0.0005}=200{,}000 updates, and the simulation shows −104-104 after exactly that many.
  3. A thousandth is not a power of 2, so a binary float cannot hold most index values exactly, and every update would add a small representation error of its own. A whole number of thousandths is exact, and the only rounding left is the one you choose on purpose. Python’s decimal module is another exact option, with the rounding rule named explicitly: see Rounding a typed decimal.

Case 2: a rocket and a conversion that was not protected

What happened. On 4 June 1996, about 40 seconds after the start of the flight sequence of the first Ariane 5 flight (flight 501), at an altitude of about 3,700 metres, the launcher veered off its flight path, broke up and exploded.
The Inquiry Board’s report names as the primary technical causes the Operand Error when converting the horizontal bias variable BH, and the lack of protection of this conversion, which caused the guidance computer (the SRI) to stop.
The report also says that not all conversions were protected because a maximum workload target of 80% had been set for the computer.

Section 2.1 of the report gives the details: the software exception came from a data conversion from 64-bit floating point to 16-bit signed integer.
The floating-point number had a value greater than what a 16-bit signed integer can represent, which resulted in the Operand Error.
The conversion instructions were not protected, although other conversions of comparable variables in the same place in the code were.
The variable BH, a horizontal bias, was far higher than expected because the early trajectory of Ariane 5 differs from that of Ariane 4, whose alignment software was reused.
The function that computed it served no purpose after lift-off, and it kept running for about 40 seconds of flight because of a requirement of Ariane 4.

What it teaches here. The drawing and the program below use illustrative numbers, not the flight’s values, only to show the idea.
A 16-bit signed integer holds the values from −32,768-32{,}768 to 32,76732{,}767⁠‏.
A value outside that range cannot be stored (an overflow), and a program must decide what happens:
wrap around (the result looks valid and is wrong), saturate (the nearest value, also wrong, but at least the right direction), or report an error.
Which is acceptable depends on who uses the value.

A number line with the range of a 16-bit signed integer shaded, the value 40,000 outside it, wrap-around giving minus 25,536 and saturation giving 32,767.
The value 40,000 does not fit in 16 bits signed. Wrapping around gives −25,536, saturating gives 32,767; both hide the problem unless an error is reported.
def wrap16(x):
    # TODO: the value a 16-bit signed integer holds after
    # wrap-around
    return x

def saturate16(x):
    # TODO: the nearest value that fits (the range is -32768
    # to 32767)
    return x

for x in (100, 32767, 32768, 40000, -40000):
    print(
        f"{x:>7}: wrap {wrap16(x):>7}   "
        f"saturate {saturate16(x):>7}"
    )
    100: wrap     100   saturate     100
  32767: wrap   32767   saturate   32767
  32768: wrap  -32768   saturate   32767
  40000: wrap  -25536   saturate   32767
 -40000: wrap   25536   saturate  -32768
Solution

The function min(a, b) is the smaller of two numbers and max(a, b) the larger, so max(-32768, min(32767, x)) clips x into the range.

def wrap16(x):
    return (x + 32768) % 65536 - 32768

def saturate16(x):
    return max(-32768, min(32767, x))

Wrap-around adds or subtracts 65,536 until the value fits, so 40,000 becomes −25,536-25{,}536⁠‏, a number of the opposite sign.
Saturation keeps the sign for a value outside the range, but clips the size to the nearest end of the range and loses how large the value was.

Questions.

  1. Decision 3 (range): what would you have asked the designers of the alignment function to document, and who should check it?
  2. Decision 5 (exceptions): the report says the conversion was left unprotected to keep the computer under an 80% workload. Is skipping the protection a sound trade? What would you protect first?
  3. For a value that steers a rocket, would you prefer wrap-around, saturation or an error that switches to a backup? Give a reason.
Suggested answers
  1. The largest value the variable can reach in every vehicle and flight the software is used in, including those it was not written for (here, a software module reused from another rocket), with the evidence behind it, reviewed by someone outside the team that wrote it.
  2. Skipping protection saves time only where the value can never leave its range, and that has to be shown, not assumed. Protect first the conversions whose inputs come from the physical world and can change when the vehicle or the conditions change.
  3. Wrap-around is the worst: it produces a plausible wrong value. Saturation is acceptable only when the guidance logic is designed for a clipped value. Reporting an error that switches to an independent backup is best, which is exactly why a stopped computer was not enough when both computers ran the same software.

Case 3: an aircraft power system and a counter

What happened. In May 2015 the US Federal Aviation Administration issued airworthiness directive 2015-09-07 for Boeing 787 aircraft:
a software counter inside the generator control units (GCUs) overflows after 248 days of continuous power.
If the four main GCUs were powered up together, all four would go into failsafe mode at the same time, which would cause a loss of all AC electrical power regardless of the phase of flight.
As interim action the directive required repeated electrical power shutdown at intervals not exceeding 120 days.

A calculation. A counter explains the number 248. A signed 32-bit counter that adds one every hundredth of a second overflows after 231100\frac{2^{31}}{100} seconds, which is 248.55248.55 days.
The directive does not state the counter’s type, so this is an inference; the computed 248.55248.55 days agrees with the 248 days of the directive.
The drawing shows how long counters of several sizes last at 100 ticks per second.

Bar chart on a logarithmic scale: a 16-bit signed counter lasts 5.5 minutes, 32-bit signed 248.6 days, 32-bit unsigned 497.1 days, 64-bit signed 2.9 billion years, with a dashed line at 20 years.
Time until a counter of hundredths of a second overflows, by size (logarithmic scale). Only the 64-bit counter lasts longer than 20 years.
TICKS_PER_SECOND = 100

def days_until_overflow(bits, signed=True):
    # TODO: days until a counter of this size, counting ticks,
    # overflows
    return 0.0

for bits, signed in (
    (16, True), (32, True), (32, False), (64, True)
):
    d = days_until_overflow(bits, signed)
    print(
        f"{bits} bit "
        f"{'signed' if signed else 'unsigned':<8} "
        f"{d:>22,.3f} days   "
        f"{d / 365.25:>20,.3f} years"
    )
16 bit signed                    0.004 days                  0.000 years
32 bit signed                  248.551 days                  0.680 years
32 bit unsigned                497.103 days                  1.361 years
64 bit signed    1,067,519,911,673.006 days      2,922,710,230.453 years
Solution

Replace the TODO line by this statement:

return (
    2 ** (bits - 1 if signed else bits)
    / TICKS_PER_SECOND / 86400
)

A signed counter has bits−1bits-1 bits for positive values; the counter counts 2bits−12^{bits-1} ticks before it overflows.
Dividing by 100 ticks per second gives seconds, and dividing by 86,400 gives days.

Questions.

  1. Decision 1 (representation): which size would you choose for a counter that must run for 20 years without a restart at 100 ticks per second, and why?
  2. Why does the directive’s remedy of switching the power off every 120 days work, and why is it only interim?
  3. Decision 5 (exceptions): all four units failing at the same moment is the dangerous part. What design choice would have limited the damage even with the same counter?
Suggested answers
  1. 20×365.25×86,400×100≈6.3×101020\times365.25\times86{,}400\times100\approx6.3\times10^{10} ticks, which needs log⁡2(6.3×1010)≈35.9\log_2(6.3\times10^{10})\approx35.9 bits, so 36 unsigned or 37 signed. In practice 64 bits, with a very large margin.
  2. Switching the power off resets the counter before it reaches 248 days; it removes the symptom, not the cause, which is why the directive called it interim action until the software could be replaced.
  3. Make sure the units do not all start counting at the same moment (stagger the restarts), or give them independent behaviour on overflow, so that one failure cannot take out all four.

Write a design note

For one of the three cases, write six lines: one for each of the five decisions, with your choice and a reason, and a sixth line saying what you would test before trusting the system.
Compare it with the suggested answers only after you have written it.

Sources