我把它键入python shell:
>>> 0.1*0.1
0.010000000000000002
Run Code Online (Sandbox Code Playgroud)
我预计0.1*0.1不是0.01,因为我知道基数10中的0.1在基数2中是周期性的.
>>> len(str(0.1*0.1))
4
Run Code Online (Sandbox Code Playgroud)
因为我看过20个字符,所以我预计会得到20分.我为什么得到4?
>>> str(0.1*0.1)
'0.01'
Run Code Online (Sandbox Code Playgroud)
好吧,这解释了为什么我len给了我4,但为什么要str回来'0.01'?
>>> repr(0.1*0.1)
'0.010000000000000002'
Run Code Online (Sandbox Code Playgroud)
为什么str圆而repr不是?(我已经阅读了这个答案,但我想知道他们如何决定何时str轮流浮动而不是什么时候)
>>> str(0.01) == str(0.0100000000001)
False
>>> str(0.01) == str(0.01000000000001)
True
Run Code Online (Sandbox Code Playgroud)
所以它似乎是浮子准确性的问题.我以为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; …Run Code Online (Sandbox Code Playgroud) 所以我打破了Python 2.6解释器,我得到了这个:
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2.1
2.1000000000000001
>>> 2.2
2.2000000000000002
>>> 2.2
2.2000000000000002
Run Code Online (Sandbox Code Playgroud)
但是在Python 2.7中,我得到了更像人类的结果,如下所示:
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 5.4
5.4
>>> 1.1
1.1
>>> 0.2
0.2
>>>
Run Code Online (Sandbox Code Playgroud)
我想问为什么会发生这种情况,我怎么可能让Python 2.6表现得像2.7?
python floating-point floating-accuracy python-2.6 python-2.7