python - Random.choices 不返回均匀分布

标签 python random statistics

我正在尝试使用 random.choices 模拟离散值的均匀分布。每次生成新集合时,表示唯一计数的键都会增加。
为什么结果是统一的([2,2])发生的可能性低于 [1,3] ?

def sim_counts(size, values=[1,-1], popsize=2):
    
    count_dict = {}
    for i in range(popsize):
        X = random.choices(values,k=size)
        _, counts = np.unique(X, return_counts=True)
        
        if len(counts) == 1:
            counts = [0,counts[0]]
        key = str(np.sort(counts))

        if key not in count_dict:
            count_dict[key] = 0
            count_dict[key] +=1
        else:
            count_dict[key] +=1
            
    return count_dict
   
sim_counts(4, values=[1,-1], popsize=10000)

>>> {'[2 2]': 3747, '[0 4]': 1319, '[1 3]': 4934}

最佳答案

作为代码整洁的一部分,您正在设置 key = str(numpy.sort(counts))这隐藏了有两种方法可以获取 [1 3] 的 key 。使用该策略。
如果没有排序再运行测试,我想你会发现结果[2 2]与您预期的一样更常见,但 [1 3] 的结果和 [3 1]而个别较少结合到更大的数量。
例如:

{'[3 1]': 2521, '[1 3]': 2550, '[2 2]': 3721, '[0, 4]': 1208}
另请参阅@barmar 的回答,以更细致地了解导致相关键的各个排列。

关于python - Random.choices 不返回均匀分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67875964/

相关文章:

python - 仅绘制某些日子的 Pandas 数据框

sql - 开源统计服务器?

python - 从多个生成器获取第一个事件

python - 在 Pandas 中创建其他列的总和值的计算列

python - google appengine, pycharm, python virtualenv 无法访问lib

programming-languages - 为什么随机不那么随机?

python - 如何在 Python 中进行 DNS 查找,包括引用/etc/hosts?

ios - SKSpriteNode 在随机路径上的平滑运动

Python-满足不同条件时如何从变量中选择

Python Pandas : dataframe. loc 返回 "KeyError: label not in [index]",但 dataframe.index 显示它是