浮点模数问题 [英] Floating Point Modulo Problem
本文介绍了浮点模数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.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屋!
查看全文