Lab 3: Floating-point arithmetic — IEEE 754 in practice#
Duration: 90 min · Materials: IEEE 754: floating-point numbers from the inside (deep dive) and Lecture 1, §1.4
Learning goals#
After this session you will be able to:
check the result of an operation on
floatnumbers with exact arithmetic (fractions.Fraction);round rational numbers according to the IEEE 754 rule (round to nearest, ties to even) and explain what ties to even is for;
show what subnormal numbers (gradual underflow) are good for;
compute the exact error of an addition (FastTwoSum) and find inputs on which compensated summation fails;
recognize computations for which no fixed precision is enough (Muller’s sequence).
The exercises come from the chapter on IEEE 754 — it contains the explanations and the examples we build on.
How to work with this set
Download the notebook (the download button at the top of the page → .ipynb), open it in VS Code, and fill in the cells marked # TWÓJ KOD (“your code”). Legend: ★ — basic exercise, ★★ — intermediate, ★★★ — optional challenge. The set ends with exercises for independent practice. The environment from Lab 1 is enough: apart from the standard library, you only need the mpmath package, which is installed together with SymPy.
import math, random, struct
from fractions import Fraction
from decimal import Decimal, localcontext, ROUND_HALF_UP, ROUND_HALF_EVEN
import mpmath
random.seed(2026)
def bity(x):
"""64 bity liczby x (float) odczytane jako liczba całkowita bez znaku."""
return struct.unpack('<Q', struct.pack('<d', x))[0]
def z_bitow(n):
"""Liczba float o podanych 64 bitach."""
return struct.unpack('<d', struct.pack('<Q', n))[0]
def losowa(zakres=40):
"""Losowa liczba float: mantysa z [1, 2), wykładnik od -zakres do zakres, losowy znak."""
return random.uniform(1, 2) * 2.0**random.randint(-zakres, zakres) * random.choice((1, -1))
print("bity(1.0) =", hex(bity(1.0)), " następna liczba po 1.0:", z_bitow(bity(1.0) + 1))
bity(1.0) = 0x3ff0000000000000 następna liczba po 1.0: 1.0000000000000002
Part A — rounding (≈ 30 min)#
A1. Drift under round half up ★#
Mathematically, \((u+v)-v=u\). In the chapter (Part 1, §3), the sequence \(u\leftarrow(u+v)-v\) computed with three digits for \(u=1.00\), \(v=0.555\) drifted under round half up: \(1.00\to1.01\to1.02\to\dots\), while with ties to even it stayed put. The function ciag computes the successive terms with the decimal module.
def ciag(u, v, cyfry, regula, kroki=8):
"""Wyrazy u, (u+v)-v, ... w arytmetyce dziesiętnej o podanej liczbie cyfr i regule zaokrąglania."""
with localcontext() as ctx:
ctx.prec, ctx.rounding = cyfry, regula
u, v = Decimal(u), Decimal(v)
wynik = [+u]
for _ in range(kroki):
u = (u + v) - v
wynik.append(u)
return wynik
print("połówki w górę:", " ".join(map(str, ciag("1.00", "0.555", 3, ROUND_HALF_UP))))
print("do parzystej: ", " ".join(map(str, ciag("1.00", "0.555", 3, ROUND_HALF_EVEN))))
połówki w górę: 1.00 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08
do parzystej: 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00
Exercise. (a) Find other \(u\), \(v\) and a number of digits for which the sequence drifts under round half up (all 9 terms are distinct) but stays put with ties to even. Start with two digits.
(b) For two digits, go through all pairs \(u=1.0,\ 1.1,\ \dots,\ 9.9\) and \(v=0.01,\ 0.02,\ \dots,\ 0.99\). How many pairs drift under round half up? What do their values of \(v\) have in common? Is there a pair for which, with ties to even, the sequence changes more than once?
(Hint: Decimal(i).scaleb(-1) is the number \(i/10\) written with one digit after the decimal point.)
# TWÓJ KOD
...
Your answer (A1(b)): …
A2. Does float(Fraction) round correctly? ★★#
The conversion float(q) for q of type Fraction should return \(q\) rounded to 53 significand bits: to the nearest machine number and, in case of a tie, to the one with the even significand. Let us check this with an independent computation.
Exercise. (a) Write a function zaokraglij(q, p) that returns the positive rational number q (a Fraction) rounded to p significand bits (round to nearest, ties to even) — also as a Fraction. Hint: find \(e\) such that \(2^e\le q<2^{e+1}\) (numerator.bit_length() and denominator.bit_length() will help), multiply \(q\) by \(2^{p-1-e}\), round to an integer (divmod(·, 1) returns the integer part and the remainder), and divide back.
(b) Check on 10,000 random fractions (numerator and denominator up to \(2^{200}\)) that Fraction(float(q)) == zaokraglij(q, 53).
(c) What do \(2^{53}+1\), \(2^{53}+3\), \(1+2^{-53}\), and \(1+3\cdot2^{-53}\) round to? Explain each case.
This exercise will come in handy in exercise Z1 at the end of the set. A reference version of the function zaokraglij is in Part 2, §4 of the chapter — look there only after you have written your own version.
# TWÓJ KOD
...
Your answer (A2(c)): …
Part B — gradual underflow (≈ 10 min)#
B1. \(x\ne y\Rightarrow x-y\ne0\) ★#
The smallest positive normal binary64 number is \(2^{-1022}\); below it lie the subnormal numbers. Thanks to them, \(x\ne y\iff x-y\ne0\) holds for finite \(x,y\) (Part 1, §4). In flush to zero (FTZ) mode, a result smaller than \(2^{-1022}\) is replaced by zero — the function bez_subnormalnych simulates this.
def bez_subnormalnych(v):
"""Tryb „flush to zero”: wynik mniejszy od najmniejszej liczby normalnej staje się zerem."""
return 0.0 if abs(v) < 2.0**-1022 else v
Exercise. Draw 100,000 random pairs \(x,y\) from the interval \([0,2^{-1020}]\) (random.uniform).
(a) Count the pairs with \(x\ne y\) for which nevertheless x - y == 0.
(b) Count the pairs with \(x\ne y\) for which bez_subnormalnych(x - y) == 0. What fraction of all pairs is this? Justify the result with a probability computation (hint: \(2^{-1020}=4\cdot2^{-1022}\)).
# TWÓJ KOD
...
Your answer (B1(b)): …
Part C — the exact error of addition (≈ 30 min)#
C1. FastTwoSum ★#
Dekker (1971): if \(|a|\ge|b|\), then with rounding to nearest (and barring overflow), for \(s=\fl(a+b)\) and \(e=\fl\bigl(b-\fl(s-a)\bigr)\) we have \(a+b=s+e\) exactly — the error of the addition is itself a machine number. The chapter (Part 2, §2) presents the TwoSum algorithm of Møller and Knuth, which does not need the condition \(|a|\ge|b|\) but performs six operations instead of three.
def fast_two_sum(a, b):
s = a + b
e = b - (s - a)
return s, e
Exercise. (a) Check on 100,000 random pairs (generated with the function losowa) that for \(|a|\ge|b|\) the decomposition is exact: Fraction(a) + Fraction(b) == Fraction(s) + Fraction(e).
(b) How often is the decomposition inexact when the arguments are given in the reverse order?
(c) Give an example with integers in which fast_two_sum gets it wrong for \(|a|<|b|\), and explain step by step what happens.
# TWÓJ KOD
...
Your answer (C1(c)): …
C2. A counterexample for Neumaier summation ★★#
Neumaier summation (Part 2, §2) collects the parts lost in the additions in the correction c. Since Python 3.12, the built-in function sum works the same way. It usually gives the correctly rounded result — but, unlike math.fsum, not always.
def neumaier(xs):
s = c = 0.0
for x in xs:
t = s + x
c += (s - t) + x if abs(s) >= abs(x) else (x - t) + s
s = t
return s + c
Exercise. Find a short list (three or four numbers; for two numbers neumaier always gives the correctly rounded result) that neumaier sums differently from math.fsum. Use Fraction to check which result is the correctly rounded sum. What does the built-in sum return for this list? (Hint: a tie. What happens when the correction c itself has to be rounded?)
# TWÓJ KOD
...
Your answer (C2): …
Part D — Muller’s sequence (≈ 15 min)#
D1. How many digits are enough? ★★#
The sequence \(u_0=2\), \(u_1=-4\), \(u_{n+1}=111-\dfrac{1130}{u_n}+\dfrac{3000}{u_nu_{n-1}}\) tends to \(6\), but computed in float it tends to \(100\) (Part 2, §7).
Exercise. (a) Compute \(u_n\) for \(n\le100\) in float, exactly (Fraction), and in mpmath with 50 and with 100 digits (with mpmath.workdps(50): ...).
(b) For each precision, find the first \(n\) for which \(|u_n-u_n^{\text{exact}}|>1\).
(c) By how much does this point shift when we add 50 digits? Explain it with the formula from the chapter: the deviation from \(6\) grows like \((100/6)^n\).
# TWÓJ KOD
...
Your answer (D1(c)): …
Exercises for independent practice#
The rules are the same as in Lab 1: the exercises are for your own practice, and each of them is a single function with the given name that returns its result. The standard library (fractions, math, struct) is enough.
Z1. Four rounding modes ★★#
Write a function zaokraglij(q, p, tryb="najblizsza") that returns the rational number q (a Fraction of any sign, including \(0\)) rounded to p significand bits (\(p\ge2\)) — as a Fraction. The modes are the four rounding modes of the IEEE 754 standard:
"najblizsza"— round to nearest, ties to even significand (the default mode),"do_zera"— toward zero (truncation),"w_gore"— toward \(+\infty\),"w_dol"— toward \(-\infty\).
The exponent is unbounded (there is no overflow and there are no subnormal numbers).
Examples: zaokraglij(Fraction(1, 3), 2) == Fraction(3, 8), zaokraglij(Fraction(-1, 3), 2, "w_gore") == Fraction(-1, 4), zaokraglij(Fraction(7, 4), 2) == 2.
Hint: exercise A2. For \(p=53\) you can check the result yourself: float(q) is the result of mode "najblizsza", and the results of the other modes are float(q) or an adjacent machine number (math.nextafter). Such a check makes sense only for \(q\) whose absolute value lies in the range of normal binary64 numbers.
Z2. Fast inverse square root in binary64 ★#
Write a function odwrotny_pierwiastek64(x, kroki) that, for a positive float \(x\), returns an approximation of \(1/\sqrt x\) computed with the trick from Part 2, §1, carried over to binary64:
the initial approximation \(y\) is the
floatwhose 64 bits are0x5FE6EB50C7B537A9 - (bity(x) >> 1)(the binary64 constant given by M. Robertson in 2012);then the Newton step
y = y * (1.5 - 0.5 * x * y * y)is appliedkrokitimes.
Paste the functions bity and z_bitow from the beginning of the set into your solution.
Examples: odwrotny_pierwiastek64(2.0, 0) == 0.7162250423950712, odwrotny_pierwiastek64(2.0, 1) == 0.706929650795464 (the exact value is \(1/\sqrt2=0.7071067811865475\ldots\)).
Check on your own computer how the largest relative error on the interval \([1,4)\) decreases after 0, 1, 2, and 3 steps. Why is it enough to examine this interval?
def zaokraglij(q, p, tryb="najblizsza"):
# TWÓJ KOD
...
def odwrotny_pierwiastek64(x, kroki):
# TWÓJ KOD
...
# Testy lokalne — odkomentuj, gdy funkcje będą gotowe:
# assert zaokraglij(Fraction(1, 3), 2) == Fraction(3, 8)
# assert zaokraglij(Fraction(-1, 3), 2, "w_gore") == Fraction(-1, 4)
# assert zaokraglij(Fraction(7, 4), 2) == 2
# assert odwrotny_pierwiastek64(2.0, 0) == 0.7162250423950712
# assert odwrotny_pierwiastek64(2.0, 1) == 0.706929650795464
# print("Testy przykładowe przechodzą.")