Ask HN: How many times will this loop run on average?
A friend of mine shared the following code snippet with me and asked me to guess how many times the loop will run on average:
for(int i = 0; i < Random(1, 100); i++);
I tried to guess the answer analytically and gussed ~50 but the empirical test was surprising to me. Can someone explain why the average is around 12?Runnable code: https://replit.com/@aalhour/RandomLoop#main.py
EDIT: Formatting.
11 comments
[ 3.4 ms ] story [ 28.9 ms ] threadE [X] = \sum_{i \in [2,100)} p(X < i)\prod_{j < i}p (X \ge j)i.
Edit: Sorry rest of reply was wrong. Had to account for not hitting until i^th loop.
edit - actually, the calculations from the other guy are probability calculations, so this is related to the median. I have given you a mean calculation, which should be related to the average. But you already mentioned that they are close ...
So, it’s 1% that the loop ends at i = 1, if it takes that hurdle 2% that it ends at i = 2, if it takes that hurdle 3% that it ends at i = 3, etc.
The calculation is easier if you phrase that this way:
It’s 99% that the loop continues at i = 1, if it takes that hurdle 98% of the rest that it continues at i = 2, if it takes that hurdle 97% that it continues at i = 3, etc.
So, the probability to make it past i = n is
Note that this isn’t necessarily the case in all languages. Pascal, for example, has a real for loop where the limit is evaluated once and the index variable cannot be changed inside the loop, so that the compiler can determine the number of iterations before starting the first iteration.Technically, “the mean is 12” does not follow at all from “p(12) sits at 50%”.
“p(12) sits at 50%” implies the median (https://en.wikipedia.org/wiki/Median) is 12, and that can differ from the mean (https://en.wikipedia.org/wiki/Arithmetic_mean) of the distribution, and the difference can be quite large.
For example, if that list were to continue
the about 44% that makes it to 13 also will make it to 1000, and the mean value will be a bit more than 442.77496045533604 (the contribution of that 44.2%)If, on the other hand, it were to continue
No result would be higher than 13, and the mean would be lower than 12.