我正在尝试创建一个程序,它检查一个等式是否创建了一个整数答案,但该方程创建的浮点数不会与整数进行比较。当它到达第一个整数时,应该是390625,它会将其打印为390625.0,并且当它到达这个数字时,它不会离开while循环。
我是编程新手,所以请保持简单。
from myro import *
from math import *
def main():
z = 3
a = 2
b = 2
x = 3
y = 3
lim = 25
c = (a**x + b**y)**(1.0/z)
while int(c) != c:
while z <= lim:
while a <= lim:
while b <= lim:
while x <= lim:
while y <= lim:
c = (a**x + b**y)**(1.0/z)
print a, b, c, x, y, z
y = y + 1
y = 3
print a, b, c, x, y, z
x = x + 1
x = 3
print a, b, c, x, y, z
b = b + 1
b = 3
print a, b, c, x, y, z
a = a + 1
a = 3
print a, b, c, x, y, z
z = z + 1
print "code cycle complete. no numbers meet criteria"
print str(a) + "^" + str(x) + " + " + str(b) + "^" + str(y) + " = " + str(c) + "^" + str(z)
main()发布于 2013-06-07 16:57:48
令我惊讶的是,每个人都认为这个问题是浮点比较造成的。在得出结论并匆忙回答之前,你们应该先看一下完整的问题/代码。
让我们回到正题。我不想解释浮点比较的问题。我没有看嵌套的while循环。考虑到当计算结果为整数时,作者需要中断循环的事实,我将回答。
Felis Vulpes,当'c‘是一个整数时,你认为循环会中断。但是您的条件"int(c) != c“并没有像您想象的那样经常被检查。1.进入循环时将检查此选项。此时,"c“的值将为2.51984209979 2。下一次检查仅在内部所有循环完成后才会发生。到那时,c的值将是25.7028456664。
您需要做的是在每次重新计算"c“时检查它的值。您的代码可能如下所示
from myro import *
from math import *
def main():
z = 3
a = 2
b = 2
x = 3
y = 3
lim = 25
c = (a**x + b**y)**(1.0/z)
#while int(c) != c:
while z <= lim:
while a <= lim:
while b <= lim:
while x <= lim:
while y <= lim:
c = (a**x + b**y)**(1.0/z)
print a, b, c, x, y, z
if int(c) == c:
print str(a) + "^" + str(x) + " + " + str(b) + "^" + str(y) + " = " + str(c) + "^" + str(z)
return
y = y + 1
y = 3
print a, b, c, x, y, z
x = x + 1
x = 3
print a, b, c, x, y, z
b = b + 1
b = 3
print a, b, c, x, y, z
a = a + 1
a = 3
print a, b, c, x, y, z
z = z + 1
print "code cycle complete. no numbers meet criteria"
main()发布于 2013-06-07 16:49:29
您必须了解浮点数在内部由硬件表示的方式。例如:
>>> x = 9999999.99
>>> y = 9999999.9900000002
>>> x == y
True
>>> x
9999999.9900000002
>>> y
9999999.9900000002(这是Python 2.6,Intel CentOS-64位;根据您的体系结构,结果可能会有所不同,但您已经明白了)
也就是说,如果你的结果恰好是100.0,当然,你会说这是一个整数。那100.000000000000000000001呢?这是方程的真实结果,还是由于浮点数在计算机硬件中的表示方式造成的一些小偏差?
您应该阅读以下内容:Floating Point Arithmetic: Issues and Limitations
也许可以考虑使用decimal包(在性能上做了一些折衷)
更新
如果使用decimal包,则可以使用余数运算符%和is_zero()方法。示例:
>>> from decimal import Decimal
>>> x = Decimal('100.00000000000001')
>>> y = Decimal('100.00000000000000')
>>> (x % 1).is_zero()
False
>>> (y % 1).is_zero()
True发布于 2013-06-07 14:48:22
abs(c - int(c)) < 0.0000001https://stackoverflow.com/questions/16977764
复制相似问题