将浮点分成桶

Wea*_*Fox 3 python floating-point rounding python-3.x

我需要创建一个浮点值的直方图,我想知道我到底该怎么做。这种幼稚的方法:

>>> 5.3/0.2
26.499999999999996
>>> 5.2/0.2
26.0
Run Code Online (Sandbox Code Playgroud)

分割然后将它们存储在 dict 中显然不起作用..round()也不够好,因为我想要大小的桶0.2。我可以制作大小合适的水桶0.1,然后将它们组合起来……谁能提出一种优雅的方法来做到这一点?

Tom*_*ech 6

使用地板除法来获得正确的 bin 编号:

>>> 5.3//0.2
26.0
Run Code Online (Sandbox Code Playgroud)

或者在真正旧版本的python上,您可以使用math.floor以下方法自己做同样的事情:

>>> math.floor(5.3 / 0.2)
26.0
Run Code Online (Sandbox Code Playgroud)

一般来说,要计算 bin 数,您可以执行以下操作:

def get_bin(x, bin_width, start=0): 
    return (x - start) // bin_width
Run Code Online (Sandbox Code Playgroud)

x你的号码在哪里,start是第一个垃圾箱的下限。

正如评论中提到的,您可能也对numpy.histogram.