Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 不返回均匀分布的随机选择_Python_Random_Statistics - Fatal编程技术网

Python 不返回均匀分布的随机选择

Python 不返回均匀分布的随机选择,python,random,statistics,Python,Random,Statistics,我试图用随机选择来模拟离散值的均匀分布。每次生成新集合时,表示唯一计数的键都会递增 为什么统一结果([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, ret

我试图用随机选择来模拟离散值的均匀分布。每次生成新集合时,表示唯一计数的键都会递增

为什么统一结果
([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}

这实际上是一个数学问题,而不是编程问题

以下是产生
[3 1]
计数的所有排列:

[1, 1, 1, -1]
[1, 1, -1, 1]
[1, -1, 1, 1]
[-1, 1, 1, 1]
[-1, -1, -1, 1]
[-1, -1, 1, -1]
[-1, 1, -1, -1]
[1, -1, -1, -1]
以下是所有的
[2]
排列:

[1, 1, -1, -1]
[1, -1, 1, -1]
[-1, 1, 1, -1]
[1, -1, -1, 1]
[-1, 1, -1, 1]
[-1, -1, 1, 1]

因此比率是8:6,这是结果的近似比率。

作为代码整理的一部分,您设置了
key=str(numpy.sort(counts))
,这隐藏了使用该策略获得
[13]
密钥的两种方法

如果您在没有排序的情况下再次运行测试,我想您会发现
[2]
的结果比您预期的更常见,但是
[13]
[3 1]
的结果在单独较少的情况下组合成更大的数量

例如:

{'[3 1]': 2521, '[1 3]': 2550, '[2 2]': 3721, '[0, 4]': 1208}

另请参阅@barmar的答案,以更细致地了解导致出现问题的键的各个排列。

设置
key=str(计数)
而不是
key=str(numpy.sort(计数))
,您将看到原因:-)哦,天哪!谢谢,如果您执行了“从集合导入defaultdict”,然后设置count_dict=defaultdict(int),那么这段代码会更干净。那么你就可以不用if/else语句来做count_dict[key]+=1了。@JonSG,如果你把它作为一个答案写下来,我会接受它。@user2263572,或者在itThanks时使用
计数器。我犯了一个新手错误。