Versions Compared

Key

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

...

Function

Domain

Range

acos(x), asin(x)

-1 <= x && x <= 1

no

atan2(y,x)

x != 0 || y != 0

no

acosh(x)

x >= 1

no

atanh(x)

-1 < x && x < 1

no

cosh(x), sinh(x)

none

yes

exp(x), exp2(x), expm1(x)

none

yes

ldexp(x, exp)

none

yes

log(x), log10(x), {{ log2(x)

x > 0

no

log1p(x)

x > -1

no

ilogb(x), logb(x)

x != 0

yes

scalbn(x, n)

none

yes

hypot( x, y)

none

yes

pow(x,y)

x > 0 || (x == 0 && y > 0) ||
(x < 0 && y is an integer)

yes

sqrt(x)

x >= 0

no

erfc(x)

none

yes

lgammma(x), tgamma(x)

( x =!= 0 ) ||&&
!(x < 0 && x is an integer)

yes

lrint(x), lround(x)

no none

yes

fmod(x,y)

y != 0

no

nextafter(x,y), nexttoward(x,y)

none

yes

fdim(x,y)

none

yes

fma(x,y,z)

none

yes

...

Range errors can usually not be prevented, so the most reliable way to handle range errors is to detect when they have occurred and act accordingly. The following approach uses C99 standard functions for floating point errors when the C99 macro math_errhandling is defined and indicates that they should be used, otherwise it examines errno.

Code Block
#include <math.h>
#if defined(math_errhandling) \
  && (math_errhandling & MATH_ERREXCEPT)
#include <fenv.h>
#endif

/* ... */

#if defined(math_errhandling) \
  && (math_errhandling & MATH_ERREXCEPT)
  feclearexcept(FE_ALL_EXCEPT);
#endif
errno = 0;

/* call the function */

#if !defined(math_errhandling) \
  || (math_errhandling & MATH_ERRNO)
if (errno != 0) {
  /* handle range error */
}
#endif
#if defined(math_errhandling) \
  && (math_errhandling & MATH_ERREXCEPT)
if (fetestexcept(FE_INVALID
               | FE_DIVBYZERO
               | FE_OVERFLOW
               | FE_UNDERFLOW) != 0)
{
  /* handle range error */
}
#endif

...

However, this code may produce a domain error if x is negative and y is not an integer, or if x is zero and y is zero. A domain error or range error may occur if x is zero and y is negative, and a range error may occur if the result cannot be represented as a double.

...

Compliant Solution

Since the pow() function can produce both domain errors and range errors, we must first check that x and y lie within the proper domain. We must also detect if a range error occurs, and act accordingly.

...