KatInterview

Build a [0,1) Sampler from Fair Coin Flips

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationprobabilityrandomized-algorithmsbit-manipulation

Last 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.