无法理解楼层功能的行为

2024-04-28 06:13:45 发布

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

我使用的是python2.7.13

我有一个简单的代码:

import math

a = [1,3,9,10,11,56,99,100,101,106,555,998,999,1000,1001,1102,9999,10000,10001,10002]

for i in a:
    print "%d : log : %f / floor : %f / int : %d" %(i, math.log(i,10), math.floor(math.log(i,10)), int(math.log(i,10)))

我想在不同的数字上尝试log函数,看看在结果上使用floor函数或将其转换为整数时会发生什么

输出为:

1 : log : 0.000000 / floor : 0.000000 / int : 0
3 : log : 0.477121 / floor : 0.000000 / int : 0
9 : log : 0.954243 / floor : 0.000000 / int : 0
10 : log : 1.000000 / floor : 1.000000 / int : 1
11 : log : 1.041393 / floor : 1.000000 / int : 1
56 : log : 1.748188 / floor : 1.000000 / int : 1
99 : log : 1.995635 / floor : 1.000000 / int : 1
100 : log : 2.000000 / floor : 2.000000 / int : 2
101 : log : 2.004321 / floor : 2.000000 / int : 2
106 : log : 2.025306 / floor : 2.000000 / int : 2
555 : log : 2.744293 / floor : 2.000000 / int : 2
998 : log : 2.999131 / floor : 2.000000 / int : 2
999 : log : 2.999565 / floor : 2.000000 / int : 2
1000 : log : 3.000000 / floor : 2.000000 / int : 2
1001 : log : 3.000434 / floor : 3.000000 / int : 3
1102 : log : 3.042182 / floor : 3.000000 / int : 3
9999 : log : 3.999957 / floor : 3.000000 / int : 3
10000 : log : 4.000000 / floor : 4.000000 / int : 4
10001 : log : 4.000043 / floor : 4.000000 / int : 4
10002 : log : 4.000087 / floor : 4.000000 / int : 4

除了数字1000之外,一切都按预期工作:您可以看到log是3.000000,但是当我使用floor函数时,它变为2.00000,整数是2,当我希望它是3时

我错过了什么?你知道吗


Tags: 函数代码inimportlogfor数字整数
2条回答

不幸的是,日志函数并不精确:

Python 2.7.14 (default, Dec 11 2017, 16:08:01) 
[GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.log(1000,10)
2.9999999999999996

当您打印它时,它将舍入到3.0000。math.log10更好:

>>> math.log10(1000)
3.0

我认为您遇到了浮点精度问题:检查math.log(1000,10)的值:

>>> math.log(1000,10)
2.9999999999999996

也就是说math.floor(math.log(1000,10))会导致2

相关问题 更多 >