[Haskell-cafe] Exception for NaN

Nick Bowler nbowler at elliptictech.com
Thu May 12 20:41:12 CEST 2011


On 2011-05-12 21:14 +0400, Grigory Sarnitskiy wrote:
> How do I make my program stop whenever it gets somewhere NaN as a
> result during a calculation? If there is no appropriate flag for ghc
> maybe there exist flags for C to use in optc.

Under IEEE 754 floating point arithmetic, any operation which produces
a quiet NaN from non-NaN inputs will also raise the "invalid" floating
point exception.  Unfortunately, GHC provides no support whatsoever for
IEEE 754 floating point exceptions.

You may neverthelesss be able to hack it, assuming appropriate hardware
and software support.  The result will not be portable.  For example,
the GNU C library provides the feenableexcept function.  Completely
untested, but on such systems, if you call feenableexcept(FE_INVALID)
from C at the start of your program, your program should receive SIGFPE
whenever the "invalid" floating point exception is raised by a floating
point operation.  This will likely cause the program to terminate.
Other systems may provide a similar mechanism.

Whether this hack actually works properly with GHC's runtime system
is another issue entirely.  Furthermore, GHC may perform program
transformations that affect the generation of these exceptions in
a negative way.

> I don't want NaN to propagate, it is merely stupid, it should be terminated.

NaN propagation is not stupid.  Frequently, components of a computation
that end up being NaN turn out to be irrelevant at a later point, in
which case the NaNs can be discarded.

Cheers,
-- 
Nick Bowler, Elliptic Technologies (http://www.elliptictech.com/)



More information about the Haskell-Cafe mailing list