Floating point list generator

Possible duplicate:
Haskell ranges and floats

If I generate a list in ghci for example

let a = [0.1,1..10]


This gives me a list a with the following entries



The last element of the list is 10.000000000000002, I guess this is just because of the floating point usage. However, compared to number 10, the result seems inconsistent, for example

last a > 10

last a < 10


Why doesn't the list creation compare if the last element is less than or equal to 10?


source to share

1 answer

Floating point arithmetic sequences stop when the value is greater than the final value plus 1/2, per prelude implementation reference :

numericEnumFrom         :: (Fractional a) => a -> [a]  
numericEnumFromThen     :: (Fractional a) => a -> a -> [a]  
numericEnumFromTo       :: (Fractional a, Ord a) => a -> a -> [a]  
numericEnumFromThenTo   :: (Fractional a, Ord a) => a -> a -> a -> [a]  
numericEnumFrom         =  iterate (+1)  
numericEnumFromThen n m =  iterate (+(m-n)) n  
numericEnumFromTo n m   =  takeWhile (<= m+1/2) (numericEnumFrom n)  
numericEnumFromThenTo n n' m = takeWhile p (numericEnumFromThen n n')  
                               p | n' >= n   = (<= m + (n'-n)/2)  
                                 | otherwise = (>= m + (n'-n)/2)


As for why you should ask the Committee, they most likely don't want the range to end "incomplete" and felt that too much would be less unpredictable. With floating point, it will always be one or the other.



All Articles