Haskell: Unexpected output for expression [0, 0.1 .. 1]

When evaluating an expression:

*main> [0, 0.1 .. 1] 

I really expected:

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

But I was very shocked to see that the way out

 [0.0,0.1,0.2,0.30000000000000004,0.4000000000000001,0.5000000000000001,0.6000000000000001,0.7000000000000001,0.8,0.9,1.0] 

Why does Haskell produce the result after evaluation?

+8
floating-point haskell range-notation
source share
2 answers

This is the result of inaccuracies in floating point values; this does not apply to Haskell. If you cannot handle the approximation inherent in a floating point, then you can use Rational with high performance:

 > 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] 

Just to score a point at home, here's Python:

 >>> 0.3 0.29999999999999999 

And here is C:

 void main() { printf("%0.17f\n",0.3); } $ gcc tc 2>/dev/null ; ./a.out 0.29999999999999999 
+19
source share

Refer to this other post . As he claims, floating point numbers are not exact on the CPU.

+3
source share

All Articles