Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Section 7.12.1 of the C standard defines two types of errors that relate specifically to math functions in math.h [ISO/IEC 9899:2011]:

domain error occurs if an input argument is outside the domain over which the mathematical function is defined.

...

The following table lists standard mathematical functions, along with any checks that should be performed on their domain, and indicates if they also throw range errors, as reported by the C standard [ISO/IEC 9899:2011]standard. If a function has a specific domain over which it is defined, the programmer should check its input values, and if a function throws range errors, the programmer should detect if a range error occurs. The standard math functions not listed in this table, such as atan(), have no domain restrictions and do not throw range errors.

...

The exact treatment of error conditions from math functions is quite complicated. C11, Section 7.12.1, defines the following behavior for floating-point overflow [ISO/IEC 9899:2011]:

A floating result overflows if the magnitude of the mathematical result is finite but so large that the mathematical result cannot be represented without extraordinary roundoff error in an object of the specified type. If a floating result overflows and default rounding is in effect, then the function returns the value of the macro HUGE_VAL, HUGE_VALF, or HUGE_VALL according to the return type, with the same sign as the correct value of the function; if the integer expression math_errhandling & MATH_ERRNO is nonzero, the integer expression errno acquires the value ERANGE; if the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, the ‘‘overflow’’ floating-point exception is raised.

...

It is also difficult to check for math errors using errno because an implementation might not set it. For real functions, the programmer can tell whether the implementation sets errno by checking whether math_errhandling & MATH_ERRNO is nonzero. For complex functions, the C standard, Section 7.3.2, simply states that "an implementation may set errno but is not required to" [ISO/IEC 9899:2011].

The System V Interface Definition, Third Edition (SVID3), provides more control over the treatment of errors in the math library. The user can provide a function named matherr that is invoked if errors occur in a math function. This function can print diagnostics, terminate the execution, or specify the desired return value. The matherr() function has not been adopted by C, so its use is not generally portable.

...

See FLP03-C. Detect and handle floating-point errors for more details on how to detect floating-point errors.

...

CERT C++ Secure Coding Standard: FLP32-CPP. Prevent or detect domain and range errors in math functions

ISO/IEC 9899:2011 Section  Section 7.3, "Complex arithmetic <complex.h>," , and Section 7.12, "Mathematics <math.h>"

...