如何检查float是否大约为整数

时间:2015-11-09 11:55:14

标签: python floating-point

在Python中,如何检查浮点数是否大约为整数,并且用户指定的最大差异是什么?

我在想is_whole(f, eps)之类的内容,其中f是有问题的值,eps是允许的最大偏差,结果如下:

>>> is_whole(1.1, 0.05)
False
>>> is_whole(1.1, 0.2)
True
>>> is_whole(-2.0001, 0.01)
True

2 个答案:

答案 0 :(得分:4)

我想出的一个解决方案是

def is_whole(f, eps):
    return abs(f - round(f)) < abs(eps)

但我不确定是否有更多的pythonic方式来做到这一点。

修改

使用abs(eps)代替eps,以避免无声的不当行为。

答案 1 :(得分:0)

我可能只是自己写一个函数。

def is_whole(f, eps):
    whole_number = round(f)
    deviation = abs(eps)
    return whole_number - deviation <= f <= whole_number + deviation
我在飞行中写了这个,如果有错误请告诉我! 希望我能提供帮助。