Alias Method

In this lesson we will be implementing the Alias method.

In the previous lesson, we sketched out the “alias method”, which enables us to implement sampling from a weighted discrete distribution in constant time.


Implementing the Alias Method

The implementation of the Alias Method is slightly tricky, but we’ll go through it carefully.

The idea is:

  • If we have nn weights then we’re going to make nn distributions.
  • Every distribution is either a singleton that returns a particular number, or we use a projection on a Bernoulli to choose between two numbers.
  • To sample, we uniformly choose from our nn distributions, and then we sample from that distribution, so each call to Sample on the weighted integer distribution does exactly two samples of other, simpler distributions.

How are we going to implement it?

The key insight is weights which are lower than the average weight “borrow” from weights which are higher than average.

Call the sum of all weights ss. We start by multiplying each weight by nn, which gives us s×ns \times n ...