Search code examples
haskellfloating-pointfractions

What's the difference between the classes Floating and Fractional in Haskell?


What is the difference is between the Floating and Fractional classes in Haskell?


Solution

  • The definitions of Fractional and Floating can be found in the documentation of the Prelude:

    class Num a => Fractional a where
        (/) :: a -> a -> a
        recip :: a -> a
        fromRational :: Rational -> a 
    

    Fractional numbers, supporting real division.

    [...]

    class Fractional a => Floating a where
        pi :: a
        exp :: a -> a
        log :: a -> a
        sqrt :: a -> a
        (**) :: a -> a -> a
        logBase :: a -> a -> a
        sin :: a -> a
        cos :: a -> a
        tan :: a -> a
        asin :: a -> a
        acos :: a -> a
        atan :: a -> a
        sinh :: a -> a
        cosh :: a -> a
        tanh :: a -> a
        asinh :: a -> a
        acosh :: a -> a
        atanh :: a -> a
    

    Trigonometric and hyperbolic functions and related functions.

    [...]

    So to translate that into English: A Fractional is any kind of number for which I can define a division:

    (/) :: Fractional a => a -> a -> a
    

    That can for instance be the case for floating point numbers, but also for fractions (where a fraction has a numerator and denominator). This is not the case for Int because if dividing an Int by an Int does not always produce an Int (well technically floating point division on a computer is not exact, but that is another story).

    A subset of Fractional numbers are Floating numbers where trigonometric are defined. It is for instance impossible that the sin of a fraction always produces a fraction: a sin is defined as an sum over an infinite sequence. Only for a very limited number of cases (like sin 0) it holds. Basically the only numbers on a computer for which trigonometric are defined (approximatively) are floating point numbers.