python是整数()故障

2024-04-24 14:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个测试,计算最小n,对于1/a+1/b=1/n,至少有x个不同的解。(a,b,n,x是正整数)

我检查了b=1/(1/n-1/a)并用is.integer()测试了b,结果令我吃惊。你知道吗

x = 2
n = 1
while(1):
    x0 = 0
    for a in range(n+1,2*n + 1):
        print '-------------'
        print 'a={}'.format(a)
        b = 1.0 / (1.0/n - 1.0/a)
        print 'b={}'.format(b)
        print 'b is integer: ' + str(b.is_integer())
        if b.is_integer():
            print 'a={} b={} n={}'.format(a,b,n)
            x0 += 1
        if x0 * 2 - 1 >= x:
            print n
            exit(0)
    n += 1

为什么b=6.0和12.0不是整数?你知道吗

-------------
a=2
b=2.0
b is integer: True
a=2 b=2.0 n=1
-------------
a=3
b=6.0
b is integer: False
-------------
a=4
b=4.0
b is integer: True
a=4 b=4.0 n=2
-------------
a=4
b=12.0
b is integer: False
-------------
a=5
b=7.5
b is integer: False
-------------
a=6
b=6.0
b is integer: True
a=6 b=6.0 n=3
...

Tags: infalsetrueformatforifisexit
2条回答

在Python2中,str不是一个数字的忠实表示,它是为了“用户友好的输出”。所以非常接近6的数字被输出为6.0。如果要查看正确的输出,请使用repr或!格式的r说明符。你知道吗

'b = {!r}'.format(b)

或者直接使用python3。:-)

如果你这样做

    print 'b is integer: ' + str(b.is_integer()), repr(b)

您将看到,由于浮点数学中的近似,这些值非常接近,但不完全是整数

相关问题 更多 >