我需要编写一个生成器,它采用一个范围,并且每次调用都会产生下一个浮点步骤。
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
当一个数字可以除以一时,我应该将该数字作为整数,但 if
语句永远不会为真。
我已经尝试过 float.is_integer()
。
最佳答案
def float_range(x, y, step):
while x <= y:
if round(x, 3) % 1 == 0:
yield int(round(x))
else:
yield x
x += step
当x加上很多倍0.1时,会出现很小的偏差。 对 x 进行舍入解决了我的小数字问题。
关于python - 检查 num 是否可以除以 1(不是 1.9、2.5,而是 1.0、6.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32442530/