我把它键入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)