无法理解地板功能的行为

时间:2018-03-02 19:49:25

标签: python python-2.7 math casting floor

我正在使用Python 2.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)))

我想尝试不同数字的日志函数,看看当我对结果使用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:你可以看到日志是3.000000但是当我使用floor函数时它变为2.00000并且整数是2,当我想要它是3

我在这里缺少什么?

2 个答案:

答案 0 :(得分:6)

不幸的是,日志功能不准确:

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

答案 1 :(得分:3)

我认为你有浮动精度问题:检查math.log(1000,10)

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

这意味着math.floor(math.log(1000,10))确实会产生2

相关问题