我已经完成了一项任务,我必须创造两个小功能,给予机会相同的“头部”或“尾部”,类似于6个面部掷骰子,1,2,3,4,5或6 .
重要提示:我无法使用randint或类似函数进行此分配.
所以我创建了这两个函数,它们利用python库中的时间(毫秒的第一个数字)函数生成一个“伪随机数”:
import time
def dice():
ctrl = False
while ctrl == False:
m = lambda: int(round(time.time() * 1000))
f = m()
d = abs(f) % 10
if d in range(1,7):
return d
ctrl = True
def coin():
m = lambda: int(round(time.time() * 1000))
f = m()
if f % 2 == 0:
return "Tails"
elif f == 0:
return "Tails"
else:
return "Heads" (EDIT: I don't know why i typed "Dimes" before)
然而,我观察到了一种倾向于将’Tails’赋予’Heads’,所以我创建了一个函数来测试100次投掷中’Tails’和’Heads’的百分比:
def _test():
ta = 0
he = 0
x = 100
while x > 0:
c = coin()
if c == "Tails":
ta += 1
else:
he += 1
x -= 1
time.sleep(0.001)
print("Tails:%s Heads:%s" % (ta, he))
测试结果是(好几次):
Tails:56 Heads:44
所以我用骰子功能做了同样的事情,结果是:
1:20 2:20 3:10 4:20 5:10 6:20
所以,正如你所看到的,由于某些原因我无法推断 – 如果是由于我或其他原因的某些错误 – 时间函数倾向于减少’3’和’5′,并再次运行测试包括所有数字(包括零,七,八和九)我已经看到这种趋势延伸到’0’和’7′.
我对此事的一些见解和意见表示感谢.
编辑:
从m = lambda:int中删除round()函数(round(time.time()* 1000))函数解决了问题 – 正如Makoto所回答的那样.
最佳答案 如果您从基于时间的随机操作获得的值彼此相等(即,由于您的计算机内部原因,您每半秒更频繁地“翻转”您的硬币),您对圆形的使用意味着您的硬币翻转功能将倾向于均数. ).
For the built-in types supporting
round()
, values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, bothround(0.5)
andround(-0.5)
are 0, andround(1.5)
is 2).
看来你的两种方法都有这种偏见;如果它们彼此之后执行得太快,或者太接近单个时间戳,那么你可以倾向于从中获得一个值:
>>> [dice() for x in range(11)]
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
>>> [coin() for x in range(11)]
['Dimes', 'Dimes', 'Dimes', 'Dimes', 'Dimes', 'Dimes', 'Dimes', 'Dimes', 'Dimes', 'Dimes', 'Dimes']
您可以做的唯一现实的事情是,如果值彼此足够接近,则重新生成时间样本,这样您就不会遇到像这样的基于时间的偏差,或者生成十个时间样本并取其平均值.原则上,如果您的计算机移动得足够快并且足够快地执行这些功能,则可能会拉出相同的时间戳,这将导致强烈的基于时间的偏差.