检查num是否可以除以1(不是1.9,2.5而是1.0,6.0)

时间:2015-09-07 16:04:45

标签: python range generator

我需要编写一个带有范围的生成器,每次调用都会产生下一个浮动步骤。

Python代码:

def float_range(x, y, step):
    while x <= y:
        x = float(x)
        if x % 1 == 0: # Here is the problem
            yield int(x)
        else:
            yield x
        x += step

当一个数字可以除以1时,我应该将数字作为整数,但if语句永远不会成立。 我已经尝试了float.is_integer()

1 个答案:

答案 0 :(得分:2)

def float_range(x, y, step):
    while x <= y:
        if round(x, 3) % 1 == 0:
            yield int(round(x))
        else:
            yield x
        x += step

当添加0.1到x的很多次时,存在小的偏差。 舍入x解决了我的小数问题。