Haskell slider function returns different results

I have a problem with the Haskell floor function - it should return "the largest integer, not greater than the argument", but the expression

floor 3.9999999999999999

returns 4, not 3. It may have something to do with the accuracy of Double , but then it should not be compiled taking into account the importance of security like Haskell, anyway in this case it returns a number greater than an argument that contradicts its definition .

+6
source share
2 answers

in this case returns a number greater than the argument, which contradicts its definition.

Returns a number equal to its argument. As you said, this is about double precision. Numbers 3.99999999999999999999 and 4 are simply equal to each other in accordance with 64-bit floating point rules.

but then it should not be compiled considering the importance of security like Haskell

The problem is that such fractional literals are of the polymorphic type Fractional a => a . That is, they should not be doubles. For example, you can write floor (3.9999999999999999 :: Rational) , which will correctly return 3, because 3.999999999999999999 can be represented as Rational without loss of precision.

If Haskell made a mistake to write 3.9999999999999999 , you would also not be able to write 3.9999999999999999 :: Rational , which would be bad. Since a Fractional literal can be represented using many different types, some of which have infinite precision, it would be a big mistake for Haskell to limit the number of legal Fractional literals based on Double constraints.

It can be argued that Haskell should limit 3.9999999999999999 when used as a Double , but not when using Rational . However, this will require instances of a class of type Fractional to declare information about their accuracy (so that Haskell can use this information to determine whether a given literal is valid for this type), which it does not currently have and which will be difficult (or impossible) ) to implement in a general, effective and user-friendly way (taking into account that the term "accuracy" can mean completely different things depending on whether we are talking about floating point numbers or fixed numbers bath point and whether they use the base 2 or 10 (or something else) to represent numbers - any of which will be possible for instances of a class of type Fractional ).

+22
source

This is not related to type safety. For example, check the value of http://babbage.cs.qc.cuny.edu/IEEE-754/ . Values ​​of 3.9999999999999999 and 4 exactly the same for floating point numbers if the length is shorter or equal to 64 bits. The return value is not greater - it is exactly the same.

If you need such high accuracy, see http://www.haskell.org/haskellwiki/Libraries_and_tools/Mathematics#Arbitrary_precision

+9
source

All Articles