我需要编写一个带有范围的生成器,每次调用都会产生下一个浮动步骤。
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()
。
答案 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解决了我的小数问题。