[Haskell-beginners] Learn You a Haskell! I have a few questions!

Brent Yorgey byorgey at seas.upenn.edu
Fri Apr 18 20:54:32 UTC 2014


On Fri, Apr 18, 2014 at 12:54:48PM -0700, Bob Ippolito wrote:
> >>
> >> ghci> [0.1, 0.3 .. 1]
> >> [0.1,0.3,0.5,0.7,0.8999999999999999,1.0999999999999999]
> >>
> >> -- ---------- End Quote
> >>
> >> Can anyone explain me why it works for the first few values, and not
> >> "completely"?
> >>
> >
> > It doesn't "work" for any of the values, it's just an artifact of how
> > they're rendered. 0.1 can't be exactly represented in binary floating
> > point, so the error compounds. Double probably shouldn't be enumerable in
> > the first place, but that's a decision we have to live with. The reason
> > that the end result is so surprising is that 1.0999999999999999 is less
> > than 1 + 0.1 and for whatever reason the way Enum is defined for Double
> > checks to see if the result is > to+(then-from) rather than <= to.
> >
> 
> To clarify, this is what is happening:
> 
>     λ> takeWhile (< 1 + 0.1) $ iterate (+0.1) 0.1
> 
> [0.1,0.2,0.30000000000000004,0.4,0.5,0.6,0.7,0.7999999999999999,0.8999999999999999,0.9999999999999999,1.0999999999999999]

Actually, the check is whether the result is > to + ((then - from)/2).
Notice that the original example is stepping by 0.2, not 0.1.

-Brent


More information about the Beginners mailing list