Question

The code below generates two random integers within range specified by argv, tests if the integers match and starts again. At the end it prints some stats about the process.

I've noticed though that increasing the value of argv reduces the percentage of tested possibilities exponentially.

This seems counter intuitive to me so my question is, is this an error in the code or are the numbers real and if so then what am I not thinking about?

#!/usr/bin/python3

import sys
import random

x = int(sys.argv[1])
a = random.randint(0,x)
b = random.randint(0,x)

steps = 1
combos = x**2

while a != b:
    a = random.randint(0,x)
    b = random.randint(0,x)
    steps += 1

percent = (steps / combos) * 100
print()
print()

print('[{} ! {}]'.format(a,b), end=' ')
print('equality!'.upper())
print('steps'.upper(), steps)
print('possble combinations = {}'.format(combos))
print('explored {}% possibilitys'.format(percent))

Thanks

EDIT For example:

./runscrypt.py 100000

will returm me something like:

[65697 ! 65697] EQUALITY!
STEPS 115867
possble combinations = 10000000000
explored 0.00115867% possibilitys

"explored 0.00115867% possibilitys" <-- This number is too low?

Was it helpful?

Solution

This experiment is really a geometric distribution.

Ie.

Let Y be the random variable of the number of iterations before a match is seen. Then Y is geometrically distributed with parameter 1/x (the probability of generating two matching integers).

The expected value, E[Y] = 1/p where p is the mentioned probability (the proof of this can be found in the link above). So in your case the expected number of iterations is 1/(1/x) = x.

The number of combinations is x^2.

So the expected percentage of explored possibilities is really x/(x^2) = 1/x.

As x approaches infinity, this number approaches 0.

In the case of x=100000, the expected percentage of explored possibilities = 1/100000 = 0.001% which is very close to your numerical result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top