浮点模数问题

Sap*_*Sun 1 python floating-point floating-accuracy

我偶然发现了一个非常奇怪的错误.阅读代码中的注释以查看错误是什么,但实际上变量modulo 1返回1(但它不等于1!).我假设有一个显示问题,浮动非常接近一个但不完全.但是,它应该模数为零.我不能轻易地测试这个案例,因为(最后%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
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 6

欢迎来到IEEE754,享受您的住宿.


Joh*_*ooy 6

打印不显示存储的数字的完整精度,您可以使用它repr()来执行此操作

>>> last=72.99999999999999
>>> print last, 1, type(last), last % 1, last - int(last)
73.0 1 <type 'float'> 1.0 1.0
>>> print last % 1 == 1
False
>>> print repr(last), 1, type(last), repr(last%1), repr(last - int(last))
72.999999999999986 1 <type 'float'> 0.99999999999998579 0.99999999999998579
>>> 
Run Code Online (Sandbox Code Playgroud)