Build a [0,1) Sampler from Fair Coin Flips
Math & Bit ManipulationModel answerLast updated
Design an algorithm that uses a fair-bit source to produce a number uniformly distributed on [0,1), and analyze its error and cost.
You have a single primitive available:
def rand_bit() -> int:
... # returns 0 or 1, each with probability 1/2, independent across calls
Your task is to use this primitive to produce a real-valued random number that is (approximately) uniform on the interval [0, 1).
Address all three parts below:
Part 1 — Algorithm
Describe and implement a procedure that draws k bits and returns a value in [0, 1). Explain the intuition behind why it works.
Part 2 — Error analysis
How close is your output distribution to a true Uniform[0, 1)? Express the approximation error as a function of k, using at least one concrete error measure. How many bits do you need for a given target precision ε?
Part 3 — Cost
How many calls to rand_bit() does your algorithm make? Is this optimal?
Bonus (strong signal) Suppose you only need to answer the question "is U < p?" for a fixed threshold p ∈ [0, 1), rather than produce the full number. Can you do better?
Hints
Hint 1
Think about what the binary representation of a number in [0,1) actually means — each bit after the decimal point is deciding which half of a progressively smaller interval the number falls into. What does that remind you of?
Hint 2
To quantify approximation error, consider the Kolmogorov (CDF) distance: the maximum difference between your output's CDF and the CDF of a true uniform. How big is each step in your output's discrete grid?
Hint 3
For the bonus, you don't need to pin down U precisely — you just need to find the first binary digit where U and p differ. Think about what happens one bit at a time and when you can stop early.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Insight: Binary Digits of a Uniform Number
A number drawn from Uniform[0, 1) has a binary expansion
U = 0.b₁ b₂ b₃ ... (base 2)
For U to be truly uniform, those bits must be i.i.d. fair coin flips: b₁ decides whether U lands in [0, 0.5) or [0.5, 1), b₂ splits that half again, and so on. This is the key structural fact — drawing k independent fair bits and treating them as the first k binary digits of U gives you a number that is, in a precise sense, as uniform as k bits allow.
Part 1 — Algorithm
Collect k bits and assemble them into an integer N, then return N / 2ᵏ.
from fractions import Fraction
from typing import Callable
def uniform01(rand_bit: Callable[[], int], k: int = 53) -> float:
"""
Sample from the uniform grid {0, 1/2^k, 2/2^k, ..., (2^k - 1)/2^k}.
Uses exactly k calls to rand_bit(). Always returns a value in [0, 1).
k must be in [0, 53] for exact IEEE double output.
"""
if not 0 <= k <= 53:
raise ValueError("k must be between 0 and 53 for exact float output")
n = 0
for _ in range(k):
n = (n << 1) | rand_bit()
return n / (1 << k) # exact: n < 2^k, so result < 1.0
Why it works: each of the 2ᵏ possible bit strings is equally likely (probability 2⁻ᵏ), and each maps to a distinct value on the grid, so the output is exactly uniform over those 2ᵏ points. The largest possible value is (2ᵏ − 1) / 2ᵏ = 1 − 2⁻ᵏ, so the algorithm never returns exactly 1.
Floating-point ceiling. An IEEE 754 double has a 53-bit significand, making k = 53 the natural cap. This is precisely how Python's random.random() is implemented. For k > 53, the division N / 2ᵏ can round up to 1.0 in floating-point arithmetic, violating the [0, 1) contract. If you need more precision, return an exact Fraction(n, 1 << k) instead.
Part 2 — Error Analysis
The output Xₖ lives on a discrete grid with spacing 2⁻ᵏ, while a true uniform takes any real value in [0, 1). Concrete error measures:
| Measure | Value |
|---|---|
| Worst-case pointwise gap to true U | < 2⁻ᵏ |
| Kolmogorov (CDF) distance | ≤ 2⁻ᵏ |
| Mean bias vs. 0.5 | 2⁻⁽ᵏ⁺¹⁾ (since E[Xₖ] = (1 − 2⁻ᵏ)/2) |
Each additional bit cuts all of these errors in half. To achieve a target precision ε, you need:
k = ⌈log₂(1/ε)⌉
For example, ε = 10⁻⁶ requires k = 20 bits; ε = 10⁻¹⁵ (near double precision) requires k = 50.
Optional refinement. Returning the cell midpoint Xₖ + 2⁻⁽ᵏ⁺¹⁾ removes the mean bias and halves the worst-case pointwise error, at the cost of never returning 0.
Part 3 — Cost
The algorithm makes exactly k calls to rand_bit(), plus O(k) work for the bit shifts. For a fixed floating-point target (k = 53) this is O(1). As a function of precision ε it is Θ(log(1/ε)).
This is also optimal. To distinguish among 1/ε equally probable cells, you need at least log₂(1/ε) bits of entropy — one bit per call — so no algorithm can do better.
Bonus — Lazy Comparison Against a Threshold
If you only need to decide whether U < p rather than produce U itself, you can often stop far earlier than k bits.
Generate the binary digits of U one at a time and compare each against the corresponding binary digit of p. The moment they differ, you know the answer: if U's bit is 0 where p's is 1, then U < p; if U's bit is 1 where p's is 0, then U ≥ p.
def less_than_p(rand_bit: Callable[[], int], p: float) -> bool:
"""
Return True iff U < p, where U ~ Uniform[0,1), using lazy bit generation.
Expected number of rand_bit() calls is 2, regardless of p.
"""
if p <= 0:
return False
if p >= 1:
return True
while True:
p *= 2
p_bit = 1 if p >= 1 else 0 # next binary digit of p
p -= p_bit
u_bit = rand_bit()
if u_bit != p_bit:
return u_bit < p_bit
# Matching bits: narrow the interval and continue
Each iteration stops with probability 1/2, so the expected number of rand_bit() calls is 2 — constant, regardless of p, and with zero approximation error. This is the lazy-evaluation view of the same binary expansion, and it is strictly more efficient than fixing k in advance whenever the comparison terminates early.
Common Mistakes
- Summing floats directly (accumulating
rand_bit() * 2**-iin a loop) introduces floating-point rounding on every step. Assembling an integer first and dividing once avoids this. - Ignoring the k > 53 overflow risk. If N / 2ᵏ rounds up to 1.0 in IEEE arithmetic, downstream code that assumes the output is in [0, 1) will silently break.
- Vague error bounds. Saying "more bits means more accurate" without a formula like 2⁻ᵏ or the inverse k = ⌈log₂(1/ε)⌉ is not a complete answer.
- Missing the optimality argument. The algorithm costs Θ(log(1/ε)) bits, and information theory says nothing can do better — mentioning this closes the complexity question cleanly.