Computer Exercise 2: Worked solutions
Algorithms, Programming, and Data Representation · Module 92313 · Exercise 2
This exercise studies binary64 values and rounding drift in financial sums. Try each task before opening its worked steps. For the personalized transaction analysis, calculate and report the values from your own assigned dataset.
Task 1: IEEE 754 bit fields
Connected topic: IEEE 754 formats (§4.4)
Task 01 · to_ieee754_bits(x)
Try first: Start by writing the 64-bit layout and the bias. Then encode one exactly representable value by hand before checking your output.
Attempted it? Open the worked steps
Task 01 · to_ieee754_bits(x) · worked solution
The function returns three fields separated by spaces: one sign bit, eleven exponent bits, and 52 fraction bits. The stored exponent uses bias 1023; the leading 1 of a normal number is implicit and is not part of the fraction field.
For x = 13.25, the binary value is 1101.012 = 1.101012 × 23. The sign is 0, the stored exponent is 3 + 1023 = 1026 = 100000000102, and the fraction begins 10101 followed by zeroes to make 52 bits.
Convert the Python float to its raw 64 bits with
struct.pack, thenint.from_bytes(..., "big")andformat(..., "064b"). Slice the 64 characters at 1 and 12; those are the sign/exponent and exponent/fraction boundaries.Check that the three returned field lengths are 1, 11, and 52 and that concatenating them gives exactly 64 bits. The fraction starts after the leading normalized 1; do not include that hidden bit.
The function (with
import struct):def to_ieee754_bits(x): raw = struct.pack("!d", x) bits = f"{int.from_bytes(raw, 'big'):064b}" sign = bits[:1] exponent = bits[1:12] mantissa = bits[12:] return f"{sign} {exponent} {mantissa}"
Task 2: Classify IEEE 754 values
Connected topic: Special values (§4.5)
Task 02 · classify_float(x)
Try first: Build a four-case decision table from the exponent and fraction fields; test signed zero and each special-value class.
Attempted it? Open the worked steps
Task 02 · classify_float(x) · worked solution
Use the sign/exponent/fraction fields from Task 1. The sign does not change whether a value is zero, subnormal, normal, infinity or NaN.
If all 11 exponent bits are zero, an all-zero fraction means zero and a nonzero fraction means subnormal. If all exponent bits are one, an all-zero fraction means infinity and a nonzero fraction means NaN. Every other exponent pattern is normal.
This works for negative zero and negative infinity too because classification depends on exponent and fraction. No float equality or
math.isnan/math.isinfcalls are needed.Check representatives: 0.0 → zero; the smallest positive subnormal → subnormal; 1.0 → normal; positive infinity → inf; and a NaN → nan. A negative zero must still classify as zero.
The function, built on Task 1:
def classify_float(x): sign, exponent, fraction = to_ieee754_bits(x).split() if exponent == "0" * 11: return "zero" if fraction == "0" * 52 else "subnormal" if exponent == "1" * 11: return "inf" if fraction == "0" * 52 else "nan" return "normal"
Task 3: Count representable floats between two values
Connected topic: IEEE 754 formats (§4.4)
Task 03 · ulp_distance(a, b)
Try first: Map the 64-bit patterns into an integer ordering that increases with numeric value, then compare the mapped integers.
Attempted it? Open the worked steps
Task 03 · ulp_distance(a, b) · worked solution
Raw IEEE bit patterns do not sort numerically across the sign boundary: negative values have the sign bit set and their magnitude ordering runs backward. First map each pattern to a monotonic integer key.
For a negative pattern, invert every bit and add one; for a nonnegative pattern, set the sign bit. The added one maps negative zero onto positive zero, so the two encodings share one numeric key. Then the absolute difference counts representable steps. Treat NaNs as unordered and define the behavior explicitly; this solution raises
ValueErrorfor them.If a and b compare equal, return zero immediately. That includes
+0.0and-0.0, which are two encodings of the same numeric value. Infinities remain valid endpoints in the ordering.Check adjacent values with
math.nextafterin both the positive and negative regions: their distance should be one. Check symmetry by swapping the arguments. Do not subtract the floats themselves; that measures numeric separation, not ULP steps.The ordering key and the distance:
def _ordered_key(x): if classify_float(x) == "nan": raise ValueError("ULP distance is undefined for NaN") raw = int(to_ieee754_bits(x).replace(" ", ""), 2) sign = 1 << 63 mask = (1 << 64) - 1 return ((~raw & mask) + 1) if raw & sign else (raw | sign) def ulp_distance(a, b): if a == b: # includes +0.0 and -0.0 return 0 return abs(_ordered_key(a) - _ordered_key(b))
Task 4: Compare ordinary and compensated sums
Connected topic: Floating-point arithmetic (§4.3)
Task 04 · naive_sum(values)
Try first: Use the same input order for both algorithms and explain why each addition rounds.
Attempted it? Open the worked steps
Task 04 · naive_sum(values) · worked solution
A floating-point addition aligns exponents, adds significands, and rounds the result back to the available precision. In binary64, a value that is too small to affect a much larger running total can disappear during that rounding.
The naive version performs the specified left-to-right accumulation from 0.0. Its answer can depend on order; cancellation can expose rounding errors introduced earlier.
For an illustrative sequence [1e16, 1.0, 1.0, -1e16], the gap between neighbouring floats at 1016 is 2, so 1016 + 1 lies exactly halfway between two of them; round-to-nearest-even keeps 1016. The naive running total therefore remains 1016 until the final cancellation and returns 0.0. The exact sum is 2.0.
Use this small example to validate behavior, but calculate the exact drift for your own assigned dataset separately. The assignment asks for the naive-versus-Kahan difference in cents: compute
100 * abs(naive_total - kahan_total)because the transaction amounts are in dollars, and report the full result in cents with the input order. For the exact difference between the two stored float results, subtract theirDecimal.from_float(...)values before multiplying by 100; do not round it to a few guessed decimal places.The function:
def naive_sum(values): total = 0.0 for value in values: total += value return total
Task 5: Implement Kahan compensated summation
Connected topic: Floating-point arithmetic (§4.3)
Task 05 · kahan_sum(values)
Try first: Track the rounding loss in a correction variable and subtract it from the next input.
Attempted it? Open the worked steps
Task 05 · kahan_sum(values) · worked solution
Kahan summation keeps a running total and a compensation for low-order bits lost in the previous addition. The correction is not an extra exact accumulator; it recovers some information that ordinary addition rounded away.
For each value, subtract the saved correction to form adjusted. Add adjusted to the total, then estimate the new lost part as (updated - total) - adjusted. Save that amount for the next iteration.
The sign in this correction formula matters. Use the consistent four-line recurrence shown below; mixing it with a variant that stores the opposite sign breaks the compensation.
Check the empty input returns 0.0 and compare the adversarial example from Task 4 with
naive_sum. Kahan often improves accuracy, but it does not guarantee the correctly rounded exact sum for every sequence.The function:
def kahan_sum(values): total = 0.0 correction = 0.0 for value in values: adjusted = value - correction updated = total + adjusted correction = (updated - total) - adjusted total = updated return total
Task 6: Detect likely catastrophic cancellation
Connected topic: Floating-point arithmetic (§4.3)
Task 06 · detect_catastrophic_cancellation(a, b)
Try first: Compare the subtraction result with the magnitude of its operands, while handling nonfinite values first.
Attempted it? Open the worked steps
Task 06 · detect_catastrophic_cancellation(a, b) · worked solution
When two large, nearly equal values are subtracted, leading digits cancel and the result may have far fewer reliable significant digits than either input. The assignment defines a practical heuristic: |a − b| ≤ max(|a|, |b|) · 2−52, provided the scale is nonzero.
First reject NaN and infinity so expressions such as infinity minus infinity do not produce misleading comparisons. Then compute the scale and apply the stated threshold exactly.
For a = 1016 and b = 1016 − 2, the scale is 1016 and the threshold is 1016 · 2−52 ≈ 2.22. The difference is 2, so the heuristic returns
True.This Boolean test flags a risk; it does not measure the actual error or prove the answer is inaccurate. The subtraction of two nearby stored floats may itself be exact, even though both operands already carry rounding error from earlier calculations.
The function:
def detect_catastrophic_cancellation(a, b): if classify_float(a) not in {"zero", "subnormal", "normal"}: return False if classify_float(b) not in {"zero", "subnormal", "normal"}: return False scale = max(abs(a), abs(b)) return scale != 0 and abs(a - b) <= scale * 2**-52
Task 7: Compare floats with a relative tolerance
Connected topic: Floating-point arithmetic (§4.3)
Task 07 · safe_float_equal(a, b, tol=1e-9)
Try first: Handle NaN and infinities explicitly, then compare the error to a scale based on the operands.
Attempted it? Open the worked steps
Task 07 · safe_float_equal(a, b, tol=1e-9) · worked solution
Exact equality is usually too strict for computed results because rounding creates small differences. A relative comparison accepts a difference no larger than tol times the larger operand magnitude.
NaN is unequal to every value, including itself. Infinities compare equal only when both are infinities with the same sign; finite arithmetic should not be used to compare them.
For finite values, let scale = max(|a|,|b|). If scale is zero, both values are zero and the difference is zero. Otherwise check |a-b| ≤ tol·scale. This is a relative-only rule; near zero it intentionally allows almost no absolute error.
Check symmetry by swapping a and b. If the application also needs an absolute tolerance near zero, the specification must say so; do not silently change this task’s stated relative tolerance.
The function:
def safe_float_equal(a, b, tol=1e-9): kind_a = classify_float(a) kind_b = classify_float(b) if kind_a == "nan" or kind_b == "nan": return False if kind_a == "inf" or kind_b == "inf": return kind_a == kind_b and ((a > 0) == (b > 0)) scale = max(abs(a), abs(b)) if scale == 0: return True return abs(a - b) <= tol * scale
Task 8: Represent money as integer cents
Connected topic: Floating-point arithmetic (§4.3)
Task 08 · FixedPointCents
Try first: Store a signed integer cent count and implement the required arithmetic and representation methods.
Attempted it? Open the worked steps
Task 08 · FixedPointCents · worked solution
Binary floating point cannot represent most decimal fractions exactly. A currency quantity restricted to cents can instead be stored as an integer number of cents; addition and subtraction then use exact integer arithmetic.
Initialize the object from an integer cent count. Addition and subtraction create a new
FixedPointCentsobject rather than changing either operand. Equality should compare both type and cent value.For the representation, use
abs(cents)withdivmod(...,100), then attach the sign and print exactly two digits after the decimal point. This also handles negative amounts such as -5 cents as -$0.05.Check 1234 reprs as $12.34, -5 reprs as -$0.05, and 125 cents + (-25 cents) gives 100 cents. Convert decimal input into cents under an explicit rounding policy; do not multiply arbitrary floats and assume the result is exact.
The class:
class FixedPointCents: def __init__(self, cents): self.cents = int(cents) def __add__(self, other): if not isinstance(other, FixedPointCents): return NotImplemented return FixedPointCents(self.cents + other.cents) def __sub__(self, other): if not isinstance(other, FixedPointCents): return NotImplemented return FixedPointCents(self.cents - other.cents) def __eq__(self, other): return (isinstance(other, FixedPointCents) and self.cents == other.cents) def __repr__(self): sign = "-" if self.cents < 0 else "" dollars, cents = divmod(abs(self.cents), 100) return f"{sign}${dollars}.{cents:02d}"
Task 9: Audit cumulative transaction drift
Connected topic: Floating-point arithmetic (§4.3)
Task 09 · audit_drift(transactions)
Try first: Compute the three totals from one normalized amount list, then track the first zero-based index where running float error exceeds one cent.
Attempted it? Open the worked steps
Task 09 · audit_drift(transactions) · worked solution
Normalize each input record first: the sheet allows dictionaries with an amount field or raw numeric amounts. Use that same ordered list for
naive_sum,kahan_sumand the running comparison.Convert each stated decimal amount to integer cents using
Decimal(and an explicit rounding rule (here, half-even to two decimal places). This prevents the conversion itself from adding a binary-float artifact to the exact ledger total.str(amount))After each running float addition, compare its exact rational value with the integer-cent total.
as_integer_ratio()gives the numerator and denominator for the stored float. Multiply the numerator by 100 to express it in cents; error exceeds one cent precisely when the resulting numerator difference is greater than the denominator.Return the totals and the first zero-based index, or
Noneif the threshold is never crossed. Validate on a tiny hand-calculated list, then run your own assigned CSV. The written justification must report your dataset’s actual drift; do not reuse another learner’s result.The function, built on Tasks 4, 5 and 8:
from decimal import Decimal, ROUND_HALF_EVEN def audit_drift(transactions): amounts = [item["amount"] if isinstance(item, dict) else item for item in transactions] naive_total = naive_sum(amounts) kahan_total = kahan_sum(amounts) fixed = FixedPointCents(0) running = 0.0 first_index = None for index, amount in enumerate(amounts): running += amount cents = int((Decimal(str(amount)) * 100).quantize( Decimal("1"), rounding=ROUND_HALF_EVEN)) fixed += FixedPointCents(cents) numerator, denominator = running.as_integer_ratio() error_num = abs(numerator * 100 - fixed.cents * denominator) if first_index is None and error_num > denominator: first_index = index return {"naive_total": naive_total, "kahan_total": kahan_total, "fixed_total_cents": fixed.cents, "first_index_error_exceeds_cent": first_index}
Task 10: Generate a summation stress case
Connected topic: Floating-point arithmetic (§4.3)
Task 10 · generate_adversarial_case(n)
Try first: Place small terms between a large positive value and its cancelling negative, then handle short lengths.
Attempted it? Open the worked steps
Task 10 · generate_adversarial_case(n) · worked solution
Choose a large number whose ULP is larger than 1.0, such as 1016 in binary64, where the ULP is 2. Adding 1.0 to that running total lands exactly halfway between two floats, and the tie rounds back to 1016, so each small term is lost.
Place −1016 last. The large terms cancel, while the naive sum has already discarded the intervening ones. From n = 3 the naive sum loses every 1.0. Kahan summation recovers the exact total from n = 4 on; at n = 3 it also returns 0, because its one stored correction is rounded away when it meets −1016. For n = 0 or 1 return an empty or zero-valued list, and for n = 2 the pair cancels.
Reject negative n because a requested list length cannot be negative. The construction is a clear stress case, not a proof of the mathematically largest possible error for every n or every summation algorithm.
Check lengths 0, 1, 2, 3 and a larger n. For n ≥ 2, the exact sum is n − 2; for n = 0 or 1, the returned zero-valued list sums to zero. Confirm that
naive_sumandkahan_sumdiffer for n ≥ 4, for example 0.0 and 8.0 at n = 10.The function:
def generate_adversarial_case(n): if n < 0: raise ValueError("n must be nonnegative") if n < 2: return [0.0] * n return [1e16] + [1.0] * (n - 2) + [-1e16]
Personal worked solutions based on the APDR Computer Exercise 2 sheet, explained in my own words. The dataset-specific drift and first-crossing results are intentionally left for each learner to calculate from their own assigned transactions. Not an official FAU publication; check course details against current materials. Made by Thanate Amornjiraporn (Focus).