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

标签 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

当一个数字可以除以一时,我应该将该数字作为整数,但 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/

相关文章:

python - 在 Windows 8.1 上安装 Boost Python,正确设置工具链

python - 如何根据用户名更改目录?

python - 对于多维范围,是否有 Python 的 range(n) 等价物?

python - 理解 : multiple values per iteration

python - 在 python 中深度复制生成器

python - 获取一些按出现次数排序的单词,一些单词应该从字符串中忽略

python - Qlabels 在最后被剪掉

key - couchdb 中两个关键范围的问题

swift - ClosedRange Firebase Swift 读写

python - 如何修改Python中生成器的最后一个元素?