I have the following code for simulating a geometric random variable where $X \sim \text{Geometric}(p)$, $0 \leq p \leq 1$, and pmf is $p(n) = (1 - p)^np$:
- Set $X = 0$.
- Generate $U \sim \text{Uniform}(0,1)$.
- If $U \leq (1-p)$ set $X = (X + 1)$ and return to (2).
- Else return $X$,
Obviously this is an inefficient approach to say generating one with, $\lfloor \text{ln}(U) / \text{ln}(1 - p)\rfloor$, since a small $p$ rarely goes through multiple iterations.
My question: With a simulation in R, I can calculate an estimated number of times we will loop through for a $p$. But I would like to have an actual equation to which I can calculate the expected number for any arbitrary $p$ to compare with more efficient algorithms.
How do I go about calculating this? Obviously, $E(U)=.5$, do we need to condition this on $1−p$?