The Crystal Programming Language Forum

RNGIterator Script

I created a RNGIterator repo for a little script I was working on to help me calculate the number of iterations needed for a chance of something happening:

It’s still a work in progress, but if anyone can make it better… please do!

Don’t really need to do this experimentally :)

Typical Random Number generators are uniformly distributed. This means each value in the given range is equally likely and the cumulative distribution function for the standard range 0 to 1 simply becomes f(x) = x.

So if we take the standard range of 0 to 1, there’s a 50% chance for a value to be greater or equal to 0.5 and thus a 50% to be lower or equal to 0.5. This means we expect it to be either of it half the time, so on average we should get to it on the second iteration.

Let’s repeat the argument for 0.1, there’s a 10% chance for a value to be below or equal 0.1 and a 90% chance for it to be greater or equal. This means we expect it to be lower 1 out of 10 times and higher 9 out of 10 times. So on average we should need 10 iterations to get a value lower and one to get one greater than 0.1.

A third time, let’s pick 0.02, so a 2% chance. So that’s one in 50 times it’s lower and 49 in 50 times its higher so we should need on average 50 tries to get a value below or equal 0.02 and still only one to get one greater or equal.

We can observe this is just 1/x :) If you change your code to use a somewhat statistically relevant amount of tests, say 100,000, you’ll observe it’ll output things very close to those values.

1 Like