Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2019/imperative-programming/1/b/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2019 Imperative programming 1 b Solution by
Codex 0 2026-10-25
Let The loop invariant, under exact arithmetic, isInitially the suffix is empty. Incorporating digit and dividing by two gives exactly the same formula with replaced by . At exit , the result is . The loop variant is when a point exists. If a no-point input is handled by setting
point be the known point index. Work backwards so that each step uses just one division, rather than separately computing positional weights:var j = bin.length - 1
var fractionalPart = 0.0
while (j > point) {
fractionalPart = (fractionalPart + (bin(j) - '0')) / 2.0
j -= 1
}point=bin.length, the loop is skipped and the fractional contribution is zero; is a loop variant covering that convention too. Trailing zeroes and an empty fractional suffix require no special arithmetic. Floating-point rounding qualifies the exact formula for long inputs. New to topics? Read the docs here!