python - 浮点取模问题

标签 python floating-point floating-accuracy

我偶然发现了一个非常奇怪的错误。阅读代码中的注释以查看错误到底是什么,但本质上,变量模 1 返回 1(但它不等于 1!)。我假设存在显示问题,其中 float 非常接近 1 但不完全是。但是,它应该以零为模。我无法轻易测试这种情况,因为 (last % 1) != 1.0 !当我尝试将相同的数字插入另一个 python 终端时,一切都正常运行。怎么回事?

def r(k,i,p):
    first = i*p
    last = first + p

    steps = int((i+1)*p) - int(i*p)
    if steps < 1:
        return p
    elif steps >= 1:
        if k == 0:
            return 1 - (first % 1)
        elif k == steps:
            if i == 189:
                print last, 1, type(last), last % 1, last - int(last)
                # Prints: 73.0 1 <type 'float'> 1.0 1.0
                print last % 1 == 1 # Returns False
            if last % 1 == 1.0:
                return 0
            return (last % 1)
        else:
            return 1

最佳答案

欢迎来到 IEEE754,enjoy your stay .

关于python - 浮点取模问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2323291/

相关文章:

python - os.environ 不返回新的和导出的环境变量

python - 如何在 Flask 中使用 session 存储用户事件信息而不需要登录?

scala - 如何比较scala中两种不同类型的对象?

c - 如何检查 2 个 float 是否相等(具有一些给定的错误值)?

Python/Opencv Float 在转换时转换为不正确的 Int

python - lask.cli.NoAppException : While importing "app", 引发了 ImportError:

python - 定量库 : building discount_curve from spots

c++ - C++程序中浮点溢出的诊断

c - pow和powf有什么区别

python - Numpy - 两个 float 与浮点类型精度之间的差异