Prevent or detect domain errors and range errors in math functions before using the results in further computations. Most of the math functions can fail, if they are given arguments which do not produce a proper result. For example, the square root of a negative number, such as sqrt(-1.0)
, has no meaning in arithmetic. This is known as a domain error; the argument is outside the domain over which the function is defined. For another example, ten raised to the one-millionth power, pow(10., 1e6)
, cannot be represented in any (current) floating representation. This is known as a range error; the result cannot be represented as a proper double number. In all such error cases, the function will return some value, but the value returned is not the correct result of the computation.
The System V Interface Definition, Third Edition (SVID3) provide more control over the treatment of errors in the math library. The user can provide a function named matherr which is invoked if errors occur in a math function. This function could print diagnostics, terminate the execution, or specify the desired return-value. The matherr()
function has not been adopted by the C standard, so its use is not generally portable.
Math errors can be prevented by carefully bounds-checking before calling functions. In particular, the following domain errors should be prevented by prior bounds-checking:
...
Code Block | ||
---|---|---|
| ||
errno = 0; /* perform computation */ if (errno != 0) { /* handle the error */ } else { /* computation succeeded */ } |
Implementation Details
System V Interface Definition, Third Edition
The System V Interface Definition, Third Edition (SVID3) provide more control over the treatment of errors in the math library. The user can provide a function named matherr which is invoked if errors occur in a math function. This function could print diagnostics, terminate the execution, or specify the desired return-value. The matherr()
function has not been adopted by the C standard, so its use is not generally portable.
Risk Assessment
Failure to properly verify arguments supplied to math functions may result in unexpected results.
...
Wiki Markup |
---|
\[[ISO/IEC 9899-1999TC3|AA. C References#ISO/IEC 9899-1999TC3]\] Section 7.12, "Mathematics <math.h>" \[[Plum 85|AA. C References#Plum 85]\] Rule 2-2 \[[Plum 9189|AA. C References#Plum 91]\] Topic 2.10, "conv - conversions and overflow" |