I'm struggling to implement a sampling scheme where arithmetic decoding is used to generate the samples.
This is based on excercise 6.3 from David MacKay's book, where you compare rejection sampling with arithmetic decoding sampling. For each symbol you want to generate with rejection sampling you have to generate an (uniformly distributed) integer from $1$ to $2^{32}$, rescale it to be in $\left(0,1\right)$ and then if your random number is less than 0.99 emit a 0 (or 1 accordingly).
To generate symbols by arithmetic coding, you feed standard random bits into an arithmetic decoder equipped with the appropriate model.
(Note: I think this works because when we compress data we go from symbols generated under P to symbols under Q - P,Q are probability distributions - and decompression works the opposite way. If we choose Q to be an easy distribution to sample from then by decoding symbols from Q we can generate symbols from P.)
I've implemented the methods in the code below:
clear all;
pdist = [0.99 0.01] ;
counts = [99 1];
N=100;
U = randi(2^32, [1 N]);
U = U/2^32;
rejection_samples(1:N) = 0;
for i=1:N
if U(i) < pdist(1) ;
rejection_samples(i) = 0;
else
rejection_samples(i) = 1;
end
end
seq = randsrc(1, N, [0 1;0.5 0.5]);
arith_samples = arithdeco(seq, counts, N);
I'm confused becuase the arith_samples variable sometimes contains a 2 (but I guess this just maps onto (0,1) as the output never seems to contain a 0 - just 1 and 2).
The answers say that the rejection sampling method takes 32 bits per generated symbol, but that arithmetic coding only takes 0.081 = $H_2\left(0.01\right)$. I can't really see that from my code.
Is there some way I could measure 'bits used'?
Also this seems a bit too good to be true - surely there are better ways of generating random numbers than just rejection sampling?
The relevant chapter is found here: