> For which values of a and b is causing the program to crash?

For which values of a and b is causing the program to crash?

Posted at: 2014-12-18 
The assert is only reached if b-a is 2 or more, so it can only fail when b==a+2.

For each choice of a, a+2 is a legal choice for b, so there is a 1/30 probability of failure no matter what a value was picked.

Each loop succeed with probablity 29/30.

Running successfully n times, requires n successes followed by 1 failure:

P(n) = (29/30)^n * (1/30) .... for n=0 to 999

The thousandth iteration is the last, so it doesn't need the 1/30 factor

P(1000) = (29/30)^1000

.... but this is negligible (about 2x10^-15). The expected value is the sum of n*P(n) for all relevant values of n. Technically, that's from n=1 to 1000, but the sum to infinity is accurate to more than 11 decimal places and easier to calculate:

Σ n*a^n = a / (1-a)2 ... over n=1 to infinity

(1/30) [ 1 + Σ n*(29/30)^n = (1/30) [(29/30) / (1/30)2]

= 29/900 * 900 = 29

That's the mean of a large number of runs, and the mean is what's usually meant by "expected value".

The median is the 0.5 probability point. The probability of *at least* n loops succeeding is (29/30)^n and that's equal to 1/2 when

n * log(29/30) = log (1/2) = -log 2

n = log(1/2) / log(29/30) = log(2) / log(30/29) ~~ 20.4

So, take your pick. Mean or median.