浮点模数问题 [英] Floating Point Modulo Problem

查看:134
本文介绍了浮点模数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了一个非常奇怪的错误。阅读代码中的注释,看看错误是什么,但实质上是一个模1的变量返回1(但不等于1!)。我假设有一个显示问题的浮动是非常接近一个,但不完全。但是,它应该是模数为零。因为(last%1)!= 1.0,所以我无法轻易测试这个例子!当我尝试将相同的数字插入另一个Python终端时,所有的行为都是正确的。这是怎么回事?

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

steps = int((i + 1)* p) - int(i * p)
如果步骤< 1:
return p
elif steps> = 1:
如果k == 0:
return 1 - (first%1)
elif k == steps :
if == 189:
print last,1,type(last),last%1,last - int(last)
#Prints:73.0 1 最后打印%1 == 1#返回False
如果最后%1 == 1.0:
返回0
返回(最后%1)
else:
return 1


解决方案

欢迎来到IEEE754, a href =http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems =noreferrer>享受您的逗留。


I've stumbled onto a very strange bug. Read the comments in the code to see what the bug is exactly, but essentially a variable modulo 1 is returning 1 (but it doesn't equal 1!). I'm assuming there is a display problem where the float is extremely close to one but not exactly. However, it should be moduloing to zero. I can't test for this case easily because (last % 1) != 1.0 ! When I try plugging the same numbers into another python terminal, everything behaves correctly. What's going on?

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

解决方案

Welcome to IEEE754, enjoy your stay.

这篇关于浮点模数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆