Reputation:
first of all, I'm not a programmer, so the answer to this might be completely obvious to someone more experienced. I was playing around with python(2.5) to solve some probability puzzle, however I kept getting results which were way off from the mark I thought they should be. So after some experimenting, I managed to identify the behaviour which was causing the problem. The script which seemed to isolate the weird behaviour is this:
import random
random.seed()
reps = 1000000
sub = [0]*10
hits = 0
first = random.randint(0,9)
while True:
second = random.randint(0,9)
if second != first:
break
sub[first] = 1
sub[second] = 1
sub[random.randint(0,9)] = 1
for i in range(1,reps):
first = random.randint(0,9)
while True:
second = random.randint(0,9)
if second != first:
break
if ((sub[first]) or (sub[second])):
hits = hits + 1
print "result: ", hits*1.0/reps*100.0
Now, this is not the problem I was initially trying to solve and the result for this script should be 34/90 or around 37.7 which is simple enough combinatorics. Sometimes, the script does give that result, however more often it gives 53.4, which seems to make no sense. This is pretty much just idle curiosity as to why exactly this script behaves like it does.
Upvotes: 1
Views: 219
Reputation: 881715
BTW, for the best way to "generate 3 different randomly distributed integers between 0 and 9 included", I heartily recommend a, b, c = random.sample(xrange(10), 3)
[[s/xrange/range/ in Python 3.0]] rather than the while
loops you're using.
Upvotes: 5
Reputation: 281495
The result depends on whether line 13:
sub[random.randint(0,9)] = 1
hits the same index as one of lines 11 or 12:
sub[first] = 1
sub[second] = 1
You protect second
from being the same as first
, but you don't protect that third entry from being the same as one of first
or second
.
Upvotes: 3