Haskell:表达式[0,0.1 .. 1]的意外输出

时间:2011-02-19 04:49:31

标签: haskell floating-point range-notation

评估表达式时:

*main> [0, 0.1 .. 1]

我其实是在期待:

 [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]

但是看到输出

我感到非常震惊
[0.0,0.1,0.2,0.30000000000000004,0.4000000000000001,0.5000000000000001,0.6000000000000001,0.7000000000000001,0.8,0.9,1.0]

为什么Haskell会在评估时产生该结果?

2 个答案:

答案 0 :(得分:19)

这是floating point值不精确的结果,并不是Haskell特有的。如果你不能处理浮点固有的近似值,那么你可以以高性价比使用Rational

> import Data.Ratio
Data.Ratio> [0,1%10.. 1%1]
[0 % 1,1 % 10,1 % 5,3 % 10,2 % 5,1 % 2,3 % 5,7 % 10,4 % 5,9 % 10,1 % 1]

要点回家,这是Python:

>>> 0.3
0.29999999999999999

这是C:

void main() { printf("%0.17f\n",0.3); }

$ gcc t.c 2>/dev/null ; ./a.out
0.29999999999999999

答案 1 :(得分:3)

请参阅this other post。正如它所述,CPU中的浮点数并不精确。