[英]Python: rounding error distorts uniform distribution
似乎你后来在代码中遇到了问题......(例如,在收集统计数据时)。 检查这个较小的片段:
import random, collections
data = collections.defaultdict(int)
for x in range(1000000):
data[round(random.random(),1)] += 1
print(data)
你会看到0
和1
当然有大约一半的其他值的样本都非常均匀。
比如我得到了:
defaultdict(<class 'int'>,
{0.4: 100083,
0.9: 99857,
0.3: 99892,
0.8: 99586,
0.5: 100108,
1.0: 49874, # Correctly about half the others
0.7: 100236,
0.2: 99847,
0.1: 100251,
0.6: 100058,
0.0: 50208}) # Correctly about half the others
你创建直方图的方法是错误的。 你应该大致得到:
0和1为50k
其他所有数字均为100k
但是你的第三个bin从0.2包含到0.3包括,导致200k,而你的第四个bin从0.3独占到0.4独占,导致零。
尝试创建边缘为0.05,0.15等的直方图,然后就不会出现这样的精度误差。
试试这个
positions = []
for dummy_i in range(10):
positions.append(random.randint (0, 10) / 10)
我认为在这里使用Numpy可能更干净,更有效:
import numpy as np
positions = np.random.random(10000)
positions = np.round(positions, decimals=3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.