我已将其输入到 python shell 中:
>>> 0.1*0.1
0.010000000000000002
我预计 0.1*0.1 不是 0.01,因为我知道以 10 为底的 0.1 在以 2 为底的情况下是周期性的。
>>> len(str(0.1*0.1))
4
我预计会得到 20 个,因为我在上面看到了 20 个字符。为什么我得到4?
>>> str(0.1*0.1)
'0.01'
好的,这解释了为什么我len
给了我 4,但为什么str
return '0.01'
?
>>> repr(0.1*0.1)
'0.010000000000000002'
为什么str
圆但是repr
不是? (我读过了这个答案 https://stackoverflow.com/a/2626364/562769,但我想知道他们是如何决定何时str
对浮点数进行四舍五入,当它不四舍五入时)
>>> str(0.01) == str(0.0100000000001)
False
>>> str(0.01) == str(0.01000000000001)
True
所以看来是浮点数精度的问题。我认为 Python 会使用 IEEE 754 单精度浮点数。所以我这样检查过:
#include <stdint.h>
#include <stdio.h> // printf
union myUnion {
uint32_t i; // unsigned integer 32-bit type (on every machine)
float f; // a type you want to play with
};
int main() {
union myUnion testVar;
testVar.f = 0.01000000000001f;
printf("%f\n", testVar.f);
testVar.f = 0.01000000000000002f;
printf("%f\n", testVar.f);
testVar.f = 0.01f*0.01f;
printf("%f\n", testVar.f);
}
I got:
0.010000
0.010000
0.000100
Python 给了我:
>>> 0.01000000000001
0.010000000000009999
>>> 0.01000000000000002
0.010000000000000019
>>> 0.01*0.01
0.0001
为什么 Python 会给我这些结果?
(我使用Python 2.6.5。如果你知道Python版本之间的差异,我也会对它们感兴趣。)