只是想理解生日悖论。使用以下代码,我发现我平均需要12 个样本来获得生日碰撞。
不能理解为什么比正常的23人得到1/2的生日碰撞几率要低很多。即使我使用 PyCrypto 中的 StrongRandom,结果也不会改变。
from random import randint
from Crypto.Random.random import StrongRandom
EXPERIMENTS_NUM = 10000
SET_SIZE = 365
SUBSET = 23
where_collision_found = list()
rnd = StrongRandom()
for experiment in range(EXPERIMENTS_NUM):
for i in range(1,SET_SIZE + 2):
collision_found = False
#Generate a subset
# subset = [rnd.randint(1, SET_SIZE) for x in range(i)]
subset = [randint(1, SET_SIZE) for x in range(i)]
# Check for collision
flags = [False for x in range(SET_SIZE + 1)]
for k in range(i):
if flags[subset[k]]: #Collision found
collision_found = True
else:
flags[subset[k]] = True
if collision_found:
# print 'Collision found in set:', subset
break
where_collision_found.append(i)
print 'average collision:', sum(where_collision_found) / float(len(where_collision_found)), 'in', EXPERIMENTS_NUM, 'experiments'
结果:
average collision: 12.1277 in 10000 experiments