[Haskell-cafe] 1/0

Dan Doel dan.doel at gmail.com
Mon Jun 16 19:45:30 EDT 2008


On Monday 16 June 2008, Evan Laforge wrote:
> So, I know this has been discussed before, but:
> > 1/0
>
> Infinity
>
> > 0/0
>
> NaN
>
> ... so I see from the archives that Infinity is mandated by ieee754
> even though my intuition says both should be NaN.
>
> Every other language throws an exception, even C will crash the
> program, so I'm guessing it's telling the processor / OS to turn these
> into signals, while GHC is turning that off.  Or something.  But then
> what about this note in Control.Exception:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char **argv)
{
  float f1 = 1.0/0.0;
  float f2 = 0.0/0.0;

  printf("%f\n%f\n", f1, f2);

  return EXIT_SUCCESS;
}

% ./Inf
inf
nan

In a Haskell program, 1/0 is floating point division. In C, 1/0 is integer 
division, which may get implicitly converted to a floating point if you 
say "float f = 1/0;". That's why you get the exception in C.

> but how about this:
> > round (0/0) :: Integer
>
> (huge negative number)
>
> Ok, so integral types don't have that exceptional value.  Shouldn't
> trying to convert NaN or Infinity to an Integral throw something?  Is
> it a performance thing?  I'd think if you're converting to Integer you
> don't really need hardware level performance anyway, so a couple of
> checks wouldn't kill anyone.

This is a (known by some) bug of sorts in the various floating point -> 
integral transformations (which ultimately boil down to decodeFloat or 
something like that at some point). It apparently doesn't know about the 
various exceptional values in the IEEE representation, so it just treats the 
representation like any other value. Infinity and NaN look like various huge 
numbers if you interpret them like any other value, so that's what you get 
out of round/ceiling/floor/etc.

It's not ideal, but I guess no one's bothered to fix it. Might be something to 
bring up on the libraries mailing list.

-- Dan


More information about the Haskell-Cafe mailing list