[ACCEPTED]-Division by zero in Haskell-divide-by-zero

Score: 43

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

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

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

Prelude> 1/(-0)
-Infinity

This is also behavior from the 12 standard.

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

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

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

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

Score: 6

I hope this helps:

Prelude> 1/0
Infinity
Prelude> -1/0
-Infinity
Prelude> 0/0
NaN

0

Score: 5

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

Example:

Prelude> 10 ** 10 ** 10
Infinity

... is definitely not 1 mathematically justified!

Score: 3

Fractional is not equal to Float (or Double) type.

Fraction 3 of 1/n where n goes to 0 so lim(n→0) 1/n 2 = +∞, lim(n→0) -1/n = -∞ and that makes 1 sense.

More Related questions