Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what languages expose IEEE 754 traps to the developer?

I'd like to play with those traps for educational purpose.

A common problem with the default behavior in numerical calculus is that we "miss" the Nan (or +-inf) that appeared in a wrong operation. Default behavior is propagation through the computation, but some operation (like comparisons) break the chain and loose the Nan, and the rest of the treatment continue without acknowledging the singularity in previous steps of the algorithm.

Sometimes we have ways to react to this kind of event : prolongating a function ("0/0 = 12 in my case"), or in time-domain simulation throwing the step away and trying with other settings (like the predictor, the step size or whatever).

So here is my question : do you know languages that expose the IEEE754 traps to the developer ? I don't feel like messing with ASM for that.

like image 315
nraynaud Avatar asked Mar 30 '09 21:03

nraynaud


1 Answers

As far as I know, you have two choices for floating point exception handling in C and C++:

First, if you disable/mask floating point exceptions (which most environments do by default), you can see whether any floating point exceptions have occurred by calling fetestexcept. fetestexcept isn't available in Visual C++, but you can steal the MinGW Runtime's implementation easily enough. (It's in the public domain.) Once an exception has been flagged, it's not cleared until you call feclearexcept, so you can call fetestexcept at the end of a series of calculations to see if any of them raised an exception. This doesn't give you the traps that you asked for, but it does let you test if problems like NaN or +/-inf have occurred and react as needed.

Second, you can enable/unmask floating point exceptions by calling feenableexcept in Linux or _controlfp in Windows. How the operating system handles a processor-generated floating point exception depends on your operating system.

  • In Linux, the OS sends a SIGFPE signal, so you can install a signal handler to catch that and set a flag that tells your routine to react appropriately.
  • In Windows, the OS invokes Structured Exception Handling to convert the processor exception into a language exception that you can catch using a __try / __catch block in C or try / catch block in C++.
  • Update: For Mac OS X, as described in this answer, you should be able to enable/unmask exceptions using _MM_SET_EXCEPTION_MASK from xmmintrin.h, and as long as you use the default compiler options (i.e., don't disable SSE), you should be able to catch exceptions using SIGFPE.

(I've written a bit more on this and other floating point issues in C and C++ in this blog posting if you're curious.)

like image 57
Josh Kelley Avatar answered Jan 05 '23 01:01

Josh Kelley