[Haskell-cafe] Why does [1.0, 3 ..4] contain 5?
Bence Kodaj
bence.kodaj at gmail.com
Thu Oct 20 12:29:18 UTC 2016
Silvio, Brandon, Ben: thanks for your instructive comments. Please allow me
to dwell on this issue for 5 more minutes - I'm really interested in your
opinion. Do you think it would be bad if we changed the definition of
numericEnumFromThenTo e1 e2 e3 in such a way that the resulting list would
never contain elements that are greater than e3 (in the e1 <= e2 case)?
I'm asking because you can actually be bitten by this quirk of enumerated
lists of Doubles (and Floats) even if you don't use floating-point literals
explicitly. Consider the following (this is how I stumbled upon this issue
actually):
-- "odd semi-factorial" of n
osf n = product [1, 3 .. n]
-- "even semi-factorial" of n
esf n = product [2, 4 .. n]
Load this into GHCi and then go:
*Main> osf 4
3
*Main> esf 4
8
*Main> osf 4 / esf 4
1.875
This last result looks total nonsense at first glance - it took me a good
15 minutes to realize what was going on. Of course, if I provide reasonable
type signatures (e.g., Integer -> Integer) for osf and esf, then the
problem goes away.
Still, to me this strange result is a lot more surprising and unexpected
than the fact that e.g., [1.0, 1.1 .. 2.3] would not actually contain (a
value close to) 2.3 if we changed the definition of numericEnumFromThenTo.
After all, it's fairly common knowledge that floating-point arithmetic is
inexact and you're not supposed to rely on precise equality of two
floating-point values, or you shouldn't be surprised if basic mathematical
identities don't hold for floating-point values (e.g., 1 + 2*0.1 /= 1 + 0.1
+ 0.1). Whereas the apparent "change" in the value of osf 4 from one line
to the next above is more baffling I believe. But what do you think?
Regards,
Bence
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20161020/0111d7f7/attachment.html>
More information about the Haskell-Cafe
mailing list