编程语言
首页 > 编程语言> > Python:舍入误差会扭曲均匀分布

Python:舍入误差会扭曲均匀分布

作者:互联网

我需要在0和1之间采样10个均匀分布的随机数.所以我认为python中的以下代码会这样做:

positions = []
for dummy_i in range(1000000):
    positions.append(round(random.random(),1))

但是,当将结果放入直方图时,结果如下所示:

Frequency of numbers rounded to 1 decimal place

因此舍入似乎破坏了random.random()生成的均匀分布.我想知道是什么导致这种情况以及如何防止这种情况发生.谢谢你的帮助!

解决方法:

您似乎在后面的代码中遇到了问题…(例如,在收集统计信息时).检查这个较小的片段:

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

标签:python,random,rounding,rounding-error
来源: https://codeday.me/bug/20190609/1202090.html