Posts
-
Simulating a Biased Coin With a Fair One
Suppose you need to simulate an event that happens \(p = 1/4\) of the time, and all you have is a fair coin. Well, that’s easy enough. Flip the coin twice. Report success if you get 2 heads, and report failure otherwise.
Suppose \(p = 1/3\) instead. That may not be a power of 2, but there is still a simple solution. Flip the fair coin twice. Report success on HH, report failure on HT or TH, and try again on TT. Each iteration takes \(2\) coin flips, and there is a \(3/4\) probability of halting, giving \(8/3\) expected coin flips.
Now, suppose you need to simulate \(p = 1/10^{100}\). Well, nothing is especially wrong with the current scheme. We need \(\lceil\log_2(10^{100})\rceil = 333\) coin flips to get enough outcomes. Then, label \(1\) case as success, \(10^{100} - 1\) as failure, and the rest as retries. For analyzing runtime, these numbers are starting to get messy, but we can at least ballpark the expected number of flips. The probability of halting is \(> 1/2\), since by construction \(2^{332} < 10^{100} < 2^{333}\), meaning the number of retry cases is less than half of all cases. Thus, the expected number of flips is at most \(666\). Yes, that is…
(•_•) ( •_•)>⌐■-■ (⌐■_■)
a devilish upper bound, but things could be worse.
(I’m not sorry.)
But, what if you need to simulate \(p = 1 / 10^{10^{100}}\)? Or simulate \(p = 1/\pi\)? In the first case, the number of flips needed is enormous. In the second, the scheme fails completely - there is no way to simulate irrational probabilities.
Easy Optimizations
We’ll get back to the irrational case later.
Recall how we simulated \(p=1/4\). The scheme reports success only on HH. So, if the first flip lands tails, we can halt immediately, since whatever way the second coin lands, we will report failure anyways. The revised algorithm is
- Flip a coin. If tails, report failure.
- Flip a coin. Report success on heads and failure on tails.
This gives \(3/2\) expected flips instead of \(2\) flips.
As another example, consider \(p = 1/5\). First, plan to flip 3 coins. Divide the 8 outcomes into 1 success case, 4 failure cases, and 3 retry cases. These can be distributed as
- accept: HHH
- failing: THH, THT, TTH, TTT
- retry: HHT, HTH, HTT
If the first coin is T, we can stop immediately. If the first two coins are HT, we can retry immediately. The only case left is HH, for which we need to see the third flip before deciding what to do.
(Some of you may be getting flashbacks to prefix-free codes. If you haven’t seen those, don’t worry, they won’t show up in this post.)
With clever rearrangement, we can bundle outcomes of a given type under as few unique prefixes as possible. This gives some improvement for rational \(p\), but still does not let us simulate irrational \(p\). For this, we need to switch to a new framework.
A New Paradigm
I did not come up with this method - I discovered it from here. I wish I had come up with it, for reasons that will become clear.
Let \(p = 0.b_1b_2b_3b_4b_5\ldots\) be the binary expansion of \(p\). Proceed as follows.
- Flip a coin until it lands on heads.
- Let \(n\) be the number of coins flipped. Report success if \(b_n = 1\) and report failure otherwise
The probability the process stops after \(n\) flips is \(1/2^n\), so the probability of success is
\[P[success] = \sum_{n: b_n = 1}^\infty \frac{1}{2^n} = p\]Regardless of \(p\), it takes \(2\) expected flips for the coin to land heads. Thus, any biased coin can be simulated in \(2\) expected flips. This beats out the other scheme, works for all \(p\) instead of only rational \(p\), and best of all you can compute bits \(b_i\) lazily, making this implementable in real life and not just in theory.
Slick, right? This idea may have been obvious to you, but it certainly wasn’t to me. After thinking about the problem more, I eventually recreated a potential chain of reasoning to reach the same result.
Bits and Pieces
(Starting now, I will use \(1\) interchangeably with heads and \(0\) interchangeably with tails.)
Consider the following algorithm.
- Construct a real number in \([0,1]\) by flipping an infinite number of coins, generating a random number \(0.b_1b_2b_3\ldots\), where \(b_i\) is the outcome of coin flip \(i\). Let this number be \(x\).
- Report success if \(x \le p\) and failure otherwise.
This algorithm is correct as long as the decimals generated follow a uniform distribution over \([0, 1]\). I won’t prove this, but for an appeal to intuition: any two bit strings of length \(k\) are generated with the same probability \(1/2^k\), and the numbers these represent are evenly distributed over the interval \([0, 1]\). As \(k \to\infty\) this approaches a uniform distribution.
Assuming this all sounds reasonable, the algorithm works! Only, there is the small problem of flipping \(\infty\)-ly many coins. However, similarly to the \(p = 1/4\) case, we can stop coin flipping as soon as as it is guaranteed the number will fall in or out of \([0, p]\).
When does this occur? For now, limit to the case where \(p\) has an infinite binary expansion. For the sake of an example, suppose \(p = 0.1010101\ldots\). There are 2 cases for the first flip.
-
The coin lands \(1\). Starting from \(0.1\), it is possible to fall inside or outside \([0,p]\), depending on how the next flips go. The algorithm must continue.
-
The coin lands \(0\). Starting from \(0.0\), it is impossible to fall outside \([0,p]\). Even if every coin lands \(1\), \(0.0111\ldots_2 = 0.1_2 < p\). (This is why \(p\) having an infinite binary expansion is important - it ensures there will be another \(1\) down the line.) The algorithm can halt and report success.
So, the algorithm halts unless the coin flip matches the \(1\) in \(p\)’s expansion. If it does not match, it succeeds. Consider what happens next. Starting from \(0.1\), there are 2 cases.
- Next coin lands \(1\). Since \(0.11 > p\), we can immediately report failure.
- Next coin lands \(0\). Similarly to before, the number may or may not end in \([0,p]\), so the algorithm must continue.
So, the algorithm halts unless the coin flip matches the \(0\) in \(p\)’s expansion. If it does not match, it fails. This gives the following algorithm.
- Flip a coin until the \(n\)th coin fails to match \(b_n\)
- Report success if \(b_n = 1\) and failure otherwise.
Note this is essentially the same algorithm as mentioned above! The only difference is the ending condition. Instead of halting on heads, the algorithm halts if the random bit does not match the “true” bit. Both happen \(1/2\) the time, so the two algorithms are equivalent.
(If you wish, you can extend this reasoning to \(p\) with finite binary expansions. Just make the expansion infinite by expanding the trailing \(1\) into \(0.1_2 = 0.0111\ldots_2\).)
Here’s a sample run of the algorithm told in pictures. The green region represents the possible values of \(x\) as bits are generated. Initially, any \(x\) is possible.
The first generated bit is \(0\), reducing the valid region to
This still overlaps \([0,p]\), so continue. The second bit is \(1\), giving
This still overlaps, so continue. The third bit is \(1\), giving
The feasible region for \(x\) no longer intersects \([0,p]\), so the algorithm reports failure.
CS-minded people may see similarities to binary search. Each bit chooses which half of the feasible region we move to, and the halving continues until the feasible region is a subset of \([0,p]\) or disjoint from \([0,p]\).
Proving Optimality
This scheme is very, very efficient. But, is it the best we can do? Is there an algorithm that does better than \(2\) expected flips for general \(p\)?
It turns out that no, \(2\) expected flips is optimal. More surprisingly, the proof is not too bad.
For a given \(p\), any algorithm can be represented by a computation tree. That tree encodes whether the algorithm succeeds, fails, or continues, based on the next bit and all previously generated bits.
Two sample computation trees for \(p = 3/4\).
With the convention that the root is level \(0\), children of the root are level \(1\), and so on, let the weight of a node be \(1/2^{\text{level}}\). Equivalently, the weight is the probability the algorithm reaches that node.
For a given algorithm and \(p\), the expected number of flips is the expected number of edges traversed in the algorithm’s computation tree. On a given run, the number of edges traversed is the number of vertices visited, ignoring the root. By linearity of expectation,
\[E[flips] = \sum_{v \in T, v \neq root} \text{weight}(v)\]To be correct, an algorithm must end at a success node with probability \(p\). Thus, the sum of weights for success nodes must be \(p\). For \(p\) with infinitely long binary expansions, we must have an infinitely deep computation tree. If the tree had finite depth \(d\), any leaf node weight would be a multiple of \(2^{-d}\), and the sum of success node weights would have at most \(d\) decimal places.
Thus, the computation tree must be infinitely deep. To be infinitely deep, every level of the tree (except the root) must have at least 2 nodes. Thus, a lower bound on the expected number of flips is
\[E[flips] \ge \sum_{k=1}^\infty 2 \cdot \frac{1}{2^k} = 2\]and as we have shown earlier, this lower bound is achievable. \(\blacksquare\)
(For \(p\) with finite binary expansions, you can do better than \(2\) expected flips. Proving the optimal bound for that is left as an exercise.)
In Conclusion…
Every coin in your wallet is now an arbitrarily biased bit generating machine that runs at proven-optimal efficiency. If you run into a bridge troll who demands you simulate several flips of a coin that lands heads \(1/\pi\) of the time, you’ll be ready. If you don’t, at least you know one more interesting thing.
-
Things I Did In My Khan Academy Internship
- Met some really cool people, both interns and full-timers.
- Ate freshly baked bread with self-churned butter. I approve of all company traditions that involve eating delicious things.
- Got to discuss Lockhart’s Lament, the zone of proximal development, and other metacognitive ideas.
- Participated in acroyoga.
- Saw fantastic Jurassic Park cosplays in celebration of Jurassic World. There’s a dinosaur costume in the office, it’s great.
- Discovered a depressing fact with Sal over lunch - an ice cream Snickers has fewer calories than a regular Snickers. So from a certain point of view, ice cream is healthier than Snickers.
- In my first week, improved quality of life in the code deploy process.
- Successfully nerdsniped three engineers for two hours with a puzzle from a puzzle hunt.
- Met a software developer who has played Hatoful Boyfriend, the pigeon dating simulator. Pigeons forever! Okosan is best bird!
- Built an automated backup system for Khan Academy’s mailing list data.
- Wrote some unit test infrastructure that made it easier to test behavior on Khan Academy endpoints.
- Found and fixed a cron job that had been silently broken for 9 months, which involved some of the best debugging I’ve ever done.
- Added ASCII art of an Arcanine to the codebase, although with less alliteration.
- Did some real, honest to God machine learning for the annual Healthy Hackathon. We computed similarities in a sparse user-video matrix. Yes, we were trying to be Netflix. No, we did not replicate Netflix in a week. Yes, it was still really cool.
- Drank far, far too much tea. It’s not my fault the office stocks unsweetened tea, and it’s also not my fault the office is in walking distance of several milk tea places.
- Speaking of which, got into a nuanced discussion about milk tea linguistics. By my understanding, “pearl milk tea” is the standard around Palo Alto, “boba” is the standard almost everywhere else, and “bubble tea” is used interchangeably with “boba” on the East Coast.
- Also got into a discussion about cloning ethics with other interns in a Chinese restaurant. We then realized we were a real life version of the dining philosophers problem. Luckily, we did not deadlock because we had sufficiently many chopsticks.
- Played D&D for the first time. I shot an arrow right into somebody’s face, it was wicked. Somewhat less wickedly, a snake almost Total Party Killed us.
- Taught two interns how to play Dominion, and totally kicked their butts while doing it.
- In return, got my butt totally kicked in Medici, Ticket to Ride, Settlers of Catan, and Tzol’kin.
- Actually won a few games of Coup!
- …after losing many more games of Coup.
- Also, gained a new appreciation for the Coup metagame. I got to pretend to be a Captain that was pretending to be an Ambassador! And I almost got away with it too.
- For the talent show, failed to solve a Rubik’s Cube blindfolded. I still won a prize: a heat pack in the shape of a heart.
-
Had a really, really good time.
-
Hello world, again
Let’s start with a story.
A long time ago (1 year 3 months ago to be exact), some dude registered a personal domain and set up a site with Blogger. He did this for two reasons: he didn’t have a personal site, and he wanted a place to practice writing. He then wrote two technical, dry posts about using Amazon Web Services to mine Litecoins, and never posted anything again.
Let’s go to the present. That dude (who was clearly me) wants to restart that blog. I’ve got things I want to say, and although Facebook statuses are okay, they don’t have formatting and they’re harder to find in the future.
If that was the only consideration, I could have used Facebook Notes, but I’ve also been looking for an opportunity to update my personal site. After looking around a bit, I’ve settled on using Jekyll and Github Pages. I chose them because:
- Blogger is a heavyweight editor that hides lots of formatting behind abstraction. That was good then, but now I want something cleaner. With Jekyll, it’s much easier to see how my site is generated. There’s no WYSIWYG editor, but I can read unrendered Markdown well enough.
- With Github Pages, I don’t need to worry about paying for web hosting.
- The site is backed by a git repo I get backups for free. I get branches for free. I get edit history for free. I can literally go through my commits and get insights into my writing process. This is what sold me on Jekyll; having complete draft history is beautiful for retrospectives on writing. To be honest, I suspect I’ll never use it, but it’s good to have the option.
In short, Jekyll lets me write blog posts with little overhead and great transparency. Over the past few days, I’ve set up the current site and ported over content from the the old one. You should see the old blog posts if you scroll down. Out with the old, in with the new…
As for next steps, I’m going to try to keep this reasonably updated. That means not all posts will be technical - I don’t have that much material. It’ll be a personal blog, and I’ll post whatever I feel like writing about. So far, I have two posts in the works. One involves reviewing fanfiction, and the other involves a webcomic. They should be going up shortly. There may be a third about biased and unbiased coins, but that one will come out later.
As for the title - although I still don’t know what I’m doing with my life, one of my goals is to be an interesting, insightful person. Unfortunately, I’m not one yet. But if I try, maybe I can get there.