4

我正在使用 RevitPythonShell,在我的代码中搜索了一个令人沮丧的错误之后,我发现问题是由于随机模块表现得很奇怪。几乎随机模块中的所有功能似乎都保留了一半的可能性。

random.sample 仅对列表的前半部分进行采样。random.uniform 生成的数字小于两个边界的平均值。random.random() 仅生成 0 到 0.5 之间的数字。

下面的代码来自 revitpythonshell 终端。谁能帮我理解发生了什么?

>>> import random
>>> #random number in the range [0.0, 1.0)
>>> for _ in range(1000):
...     if random.random() >= 0.5: print("hello !!")
... 
>>> # nothing got printed !!!
>>> max = 0
>>> for _ in range(1000):
...     rand = random.random()
...     if rand > max: max = rand
... 
>>> max
0.499520565070528
>>> # looks like the random values are being capped at 0.5 !!
>>> 
>>> nums = list(range(10))
>>> for _ in range(1000): 
...     if random.sample(nums, 1)[0] >= 5: print("hello")
... 
>>> # nothing got printed !!
>>> # half of the range of possibilities goes untouched for some reason
>>> a = 3.5
>>> b = 4.75
>>> half = (a+b)/2
>>> for _ in range(1000):
...     if random.uniform(a,b) > half: print("Hello !!!")
... 
>>> # nothing got printed !! all the values are less than half !!!
>>> #looks like all the functions of the random module have this behavior
>>> 
4

0 回答 0