Floating point trap handling -- is it possible?
Don Clugston
dac at nospam.com.au
Mon Jul 24 03:10:13 PDT 2006
I notice that the in the D docs, and in std.c.fenv, there is no mention
of floating-point trap handling. Is it even feasible to handle traps in
a portable manner?
Here's a theoretical example of overflow/underflow handling that would
allow computation at maximum speed for normal arrays, and still yield
correct results for (say) arr [] = [ real.max, real.max, real.min,
real.min, 3.0 ];
which would ordinarily cause an overflow.
import mythical.floatTrap;
real product(real [] arr)
{
int numOverflows=0;
real prod = 1.0;
floatTrap(OVERFLOW, (real x) { prod = x; ++numOverflows; });
floatTrap(UNDERFLOW, (real x) { prod = x; --numOverflows; });
scope(exit) floatTrap(OVERFLOW, null); // restore previous trap state
scope(exit) floatTrap(UNDERFLOW, null);
foreach(x; arr) { prod*=x; }
// now the total product is prod + pow(2, numOverflows*real.wrap)
if (numOverflows==0) return prod;
else {
// do something sensible in this situation
}
}
where
float.wrap = 192 = 0xC0
double.wrap = 1536 = 0x600
real.wrap = 0x6000
are intrinsic floating-point constant properties not currently supported
by D (and which would be needed only if D could support traps).
I have no idea if this is feasible across the OSes supported by D; for
example, it requires that the OS save the floating point exception
handler states between threads. Walter once made a comment that
signalling NaNs are poorly supported by OSes; is trap handling the reason?
More information about the Digitalmars-d
mailing list