0

I have been baffled by this behavior

Prelude> [1, 3 .. 6]
[1,3,5]
Prelude> [1.0, 3.0 .. 6.0]
[1.0,3.0,5.0,7.0]

I've found in Haskell 98 report that

For Float and Double, the semantics of the enumFrom family is given by the rules for Int above, except that the list terminates when the elements become greater than e3+i/2 for positive increment i, or when they become less than e3+i/2 for negative i.

My question is: why is it so?

matiasg
  • 1,927
  • 2
  • 24
  • 37
  • 2
    This is going to be all to do with floating-point rounding errors. In general, anytime you compare two floating-point values, you probably want a small error tolerance [which is proportional to the size of the numbers involved]. – MathematicalOrchid May 05 '15 at 14:20
  • @MathematicalOrchid: right, though arguably, over-shooting by 1 is not OK under any sensible rounding-error tolerance! The real problem is that Haskell ranges are in principle a bit weird, in a way that's particularly obvious when you throw in in-exact types like floating-point numbers. – leftaroundabout May 05 '15 at 14:29
  • Yes, in this case the tolerance seems far away from rounding problems. The previous question, which I couldn't find before asking, has the discussion I wanted to read. Thanks, @leftaroundabout ! – matiasg May 05 '15 at 14:36
  • 1
    The issue is that `6.0` falls exactly in the middle of the "natural" steps `5.0,7.0`. If you stop at `5.0` you are stopping `1.0` earlier than the boundary, if you stop at `7.0` you are `1.0` after the boundary. The error is `1.0` in both cases. You might argue that `5.0` is more natural, and I would agree, but it's tricky to find a "perfect" convention which fist all uses. – chi May 05 '15 at 14:52

0 Answers0