...
Operating System | Handling FP errors | |
---|---|---|
Linux | C99 FP functions - These functions are declared in | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9ce6b8a1093457b9-98557cbd-4a0c4561-95419b62-1be6db60edcaf63f06e5cb60"><ac:plain-text-body><![CDATA[ | Windows | Structured Exception Handling - user defined handler |
...
Code Block | ||
---|---|---|
| ||
fpOper_noErrorChecking() { /* ... */ double a = 1e-40, b, c = 0.1; float x = 0, y; /* inexact and underflows */ y = a; /* divide by zero operation */ b = y / x; /* inexact (loss of precision) */ c = sin(30) * a; /* ... */ } |
Compliant Solution 1
This compliant solution uses C99 standard functions to handle floating point errors.
Code Block | ||
---|---|---|
| ||
#include <fenv.h> fpOper_fenv() { double a = 1e-40, b, c = 0.1; float x = 0, y; int fpeRaised; /* ... */ feclearexcept(FE_ALL_EXCEPT); /* Store a into y is inexact and underflows: */ y = a; fpeRaised = fetestexcept(FE_ALL_EXCEPT); /* fpeRaised has FE_INEXACT and FE_UNDERFLOW */ feclearexcept(FE_ALL_EXCEPT); /* divide by zero operation */ b = y / x; fpeRaised = fetestexcept(FE_ALL_EXCEPT); /* fpeRaised has FE_DIVBYZERO */ feclearexcept(FE_ALL_EXCEPT); c = sin(30) * a; fpeRaised = fetestexcept(FE_ALL_EXCEPT); /* fpeRaised has FE_INEXACT */ feclearexcept(FE_ALL_EXCEPT); /* ... */ } |
Compliant Solution 2 (Windows)
MS Visual Studio 2008 and earlier does not support C99 functions to handle floating point errors. Windows provides an alternative method to get floating point exception code using _statusfp()
, _statusfp2()
, and _clearfp()
.
Code Block | ||
---|---|---|
| ||
fpOper_usingStatus() { /* ... */ double a = 1e-40, b, c; float x = 0, y; unsigned int rv = _clearfp() ; /* Store into y is inexact and underflows: */ y = a; rv = _clearfp() ; /* rv has _SW_INEXACT and _SW_UNDERFLOW */ /* zero-divide */ b = y / x; rv = _clearfp() ; /* rv has _SW_ZERODIVIDE */ /* inexact */ c = sin(30) * a; rv = _clearfp() ; /* rv has _SW_INEXACT */ /* ... */ } |
Compliant Solution 3 (Windows)
MS Visual Studio 2008 also uses structured exception handling (SEH) to handle floating point operation. Using the SEH allows the programmer to change the results of the floating point operation that caused the error condition. Using SEH also provides more information about the error condition.
...