5

My uniform random number generator can only produce integers in the range $0 \leq n \leq 255$. I need to use the output from this random number generator to generate another uniformly random integer in the range $0 \leq m \leq 209$. How can I do this?

Context: I need to randomly select an item from a list of 210 items using a random number supplied to me in the form of 8 random binary digits. I cannot change the range of the random number supplied to me.

EDIT: Some of the helpful comments suggest that I should use "rejection sampling". However, I would prefer a solution that has a guarantee on its maximum running time when implemented in a computer program.

Flux
  • 359

1 Answers1

1

(Summarizing the discussion from the comments with added quantitative insights)

Within the given constraints, achieving both - an exactly uniform distribution as well as deterministically finite runtime, is impossible. We can tradeoff one for the other.

Method 1- Rejection Sampling

This method achieves exactly uniform distribution but does not have a deterministic runtime. The idea is, generate $n \in [0, 255]$. If $n \geq 210$, repeat the process; otherwise return the value.

Let $T$ be the number of trials, then the distribution follows: $$\Pr[T>k]=\left(1−\frac{210}{256}\right)^k $$

This gives, $\mathbb{E}[T] \approx 1.22$, and $\Pr[T > 5] \approx 0.02\% $ which is extremely low.
$\Pr[T > 120]$ is much lesser than $1 \over {\text{# atoms in the universe}}$

Method 2- Multiply-and-floor

Each trial of the rng gives 1 byte. Draw $k$ independent bytes, and concat to get the integer $X$. Then, consider $$ m = \left\lfloor X \times \dfrac{210}{2^{8k}} \right\rfloor \in [0, 209] $$

This runs in exactly $k$ draws, but is slightly biased because $2^{8k}$ is never a multiple of 210.

Let's quantify the bias. Exactly $ R_k = 2^{8k}\bmod 210$ of the 210 output-values get a slightly higher probability. Let's call this set $Q_k$. We have, $$ \Pr[m=i] = \begin{cases} \dfrac{\lfloor2^{8k}/210\rfloor+1}{2^{8k}} & i\in Q_k \\ \dfrac{\lfloor2^{8k}/210\rfloor}{2^{8k}} & \text{otherwise}. \end{cases} $$

Maximum bias, from the expected $1/210$ is then approx $2^{-8k}$.
With just $k=1$, the bias is already less than $0.5\%$.

whoisit
  • 4,028
  • 1
  • 8
  • 29
  • 1
    This is a well-organized and thoughtful answer, but it means we now have $16$ very similar questions with similar answers instead of just $15$. – David K May 26 '25 at 01:51