Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division by zero in Haskell

I found a quite strange inconsistency between the behaviour of div and /.

*ghci> :t 1 `div` 0
1 `div` 0 :: Integral a => a
*ghci> :t 1 / 0
1 / 0 :: Fractional a => a
*ghci> 1 / 0
Infinity
*ghci> 1 `div` 0
*** Exception: divide by zero

I was quite surprised to notice that the fractional division by zero leads to Infinity, whereas div correctly leads to an exception. A NaN could be acceptable too for /, but why Infinity? There is no mathematical justification for such a result. Do you know the reason for this, please?

like image 805
Riccardo T. Avatar asked Feb 19 '12 22:02

Riccardo T.


3 Answers

The reason that div does not return Infinity is simple--there is no representation for infinity in the Integer type.

/ returns Infinity because it follows the IEEE 754 standard (which describes floating point number representations) since the default Fractional type is Double. Other languages with floating point numbers (e.g. JavaScript) also exhibit this behavior.

To make mathematicians cringe even more, you get a different result if you divide by negative 0, despite the fact that -0 == 0 for floats:

Prelude> 1/(-0)
-Infinity

This is also behavior from the standard.

If you use a different fractional type like Rational, you will get the behavior you expect:

Prelude> 1 / (0 :: Rational)
*** Exception: Ratio.%: zero denominator

Coincidentally, if you're wondering about why Integer and Double are the types in question when your actual operation does not reference them, take a look at how Haskell handles defaulting types (especially numeric types) in the report.

The short version is that if you have an ambiguous type from the Num class, Haskell will first try Integer and then Double for that type. You can change this with a default (Type1, Type2...) statement or turn it off with a default () statement at the module level.

like image 55
Tikhon Jelvis Avatar answered Nov 10 '22 21:11

Tikhon Jelvis


I hope this helps:

Prelude> 1/0
Infinity
Prelude> -1/0
-Infinity
Prelude> 0/0
NaN
like image 22
9000 Avatar answered Nov 10 '22 22:11

9000


It may not be that way for a mathematical reason. Infinity is used sometimes as a "sin bin": everything that doesn't work in our system cleanly, put it in there.

Example:

Prelude> 10 ** 10 ** 10
Infinity

... is definitely not mathematically justified!

like image 5
amindfv Avatar answered Nov 10 '22 23:11

amindfv