Mathematics
***********

This chapter contains information about functions for performing mathematical computations, such as trigonometric functions.  Most of these functions have prototypes declared in the header file math.h.

For all functions which take a single floating-point argument and for several other functions as well there are three different functions available for the type double, float, and long double.  The double versions of the functions are mostly defined even in the ISO C 89 standard.  The float and long double variants are introduced in the numeric extensions for the C language which are part of the ISO C 9X standard.

Which of the three versions of the function should be used depends on the situation.  For most functions and implementation it is true that speed and precision do not go together.  I.e., the float versions are normally faster than the double and long double versions.  On the other hand the long double version has the highest precision.  One should always think about the actual needs and in case of double using double is a good compromise.

Domain and Range Errors
=======================

Many of the functions listed in this chapter are defined mathematically over a domain that is only a subset of real numbers.  For example, the acos function is defined over the domain between -1 and 1.  If you pass an argument to one of these functions that is outside the domain over which it is defined, the function sets errno to EDOM to indicate a domain error.  On machines that support IEEE 754 floating point, functions reporting error EDOM also return a NaN.

Some of these functions are defined mathematically to result in a complex value over parts of their domains.  The most familiar example of this is taking the square root of a negative number.  The functions in this chapter take only real arguments and return only real values; therefore, if the value ought to be nonreal, this is treated as a domain error.

A related problem is that the mathematical result of a function may not be representable as a floating point number.  If magnitude of the correct result is too large to be represented, the function sets errno to ERANGE to indicate a range error, and returns a particular very large value (named by the macro HUGE_VAL) or its negation (-HUGE_VAL).

If the magnitude of the result is too small, a value of zero is returned instead.  In this case, errno might or might not be set to ERANGE.

The only completely reliable way to check for domain and range errors is to set errno to 0 before you call the mathematical function and test errno afterward.  As a consequence of this use of errno, use of the mathematical functions is not reentrant if you check for errors.

 -- Macro: double HUGE_VAL
     An expression representing a particular very large number.  On machines that use IEEE 754/IEEE 854 floating point format, the value is ``infinity''.  On other machines, it's typically the largest positive number that can be represented.

     The value of this macro is used as the return value from various mathematical double returning functions in overflow situations.

 -- Macro: float HUGE_VALF
     This macro is similar to the HUGE_VAL macro except that it is used by functions returning float values.

     This macro is introduced in ISO C 9X.

 -- Macro: long double HUGE_VALL
     This macro is similar to the HUGE_VAL macro except that it is used by functions returning long double values.  The value is only different from HUGE_VAL if the architecture really supports long double values.

     This macro is introduced in ISO C 9X.

A special case is the ilogb function see Exponents and Logarithms.  Since the return value is an integer value, one cannot compare with HUGE_VAL etc.  Therefore two further values are defined.

 -- Macro: int FP_ILOGB0
     This value is returned by ilogb if the argument is 0.  The numeric value is either INT_MIN or -INT_MAX.

     This macro is introduced in ISO C 9X.

 -- Macro: int FP_ILOGBNAN
     This value is returned by ilogb if the argument is NaN.  The numeric value is either INT_MIN or INT_MAX.

     This macro is introduced in ISO C 9X.

For more information about floating-point representations and limits, see Floating Point Parameters.  In particular, the macro DBL_MAX might be more appropriate than HUGE_VAL for many uses other than testing for an error in a mathematical function.

Exceptions in Math Functions
============================

Due to the restrictions in the size of the floating-point number representation or the limitation of the input range of certain functions some of the mathematical operations and functions have to signal exceptional situations.  The IEEE 754 standard specifies which exceptions have to be supported and how they can be handled.

IEEE 754 specifies two actions for floating-point exception: taking a trap or continuing without doing so.  If the trap is taken a (possibly) user defined trap handler is called and this function can correct the argument or react somehow else on the call.  If the trap handler returns, its return value is taken as the result of the operation.

If no trap handler is called each of the known exceptions has a default action.  This consists of setting a corresponding bit in the floating-point status word to indicate which kind of exception was raised and to return a default value, which depends on the exception (see the table below).

The exceptions defined in IEEE 754 are:

Invalid Operation
     This exception is raised if the given operands are invalid for the operation to be performed.  Examples are (see IEEE 754, section 7):

      1. Any operation on a signalling NaN.

      2. Addition or subtraction; magnitude subtraction of infinities such as (+oo) + (-oo).

      3. Multiplication: 0 x oo.

      4. Division: 0/0 or oo/oo.

      5. Remainder: x REM y, where y is zero or x is infinite.

      6. Square root if the operand is less then zero.

      7. Conversion of an internal floating-point number to an integer or to a decimal string when overflow, infinity, or NaN precludes a faithful representation in that format and this cannot otherwise be signaled.

      8. Conversion of an unrecognizable input string.

      9. Comparison via predicates involving < or >, without ?, when the operands are unordered.  (?> means the unordered greater relation, see FP Comparison Functions).

     If the exception does not cause a trap handler to be called the result of the operation is taken as a quiet NaN.

Division by Zero
     This exception is raised if the divisor is zero and the dividend is a finite nonzero number.  If no trap occurs the result is either +oo or -oo, depending on the signs of the operands.

Overflow
     This exception is signalled whenever the result cannot be represented as a finite value in the precision format of the destination.  If no trap occurs the result depends on the sign of the intermediate result and the current rounding mode (IEEE 754, section 7.3):

      1. Round to nearest carries all overflows to oo with the sign of the intermediate result.

      2. Round toward 0 carries all overflows to the precision's largest finite number with the sign of the intermediate result.

      3. Round toward -oo carries positive overflows to the precision's largest finite number and carries negative overflows to -oo.

      4. Round toward oo carries negative overflows to the precision's most negative finite number and carries positive overflows to oo.

Underflow
     The underflow exception is created when an intermediate result is too small for the operation or if the operations result rounded to the destination precision causes a loss of accuracy by approximating the result by denormalized numbers.

     When no trap is installed for the underflow exception, underflow shall be signaled (via the underflow flag) only when both tininess and loss of accuracy have been detected.  If no trap handler is installed the operation continues with an inprecise small value or zero if the destination precision cannot hold the small exact result.

Inexact
     This exception is signalled if the rounded result is not exact (such as computing the square root of two) or the result overflows without an overflow trap.

To control whether an exception causes a trap to occur all IEEE 754 conformant floating-point implementations (either hardware or software) have a control word.  By setting specific bits for each exception in this control word the programmer can decide whether a trap is wanted or not.

ISO C 9X introduces a set of function which can be used to control exceptions.  There are functions to manipulate the control word, to query the status word or to save and restore the whole state of the floating-point unit.  There are also functions to control the rounding mode used.

Controlling the FPU status word
-------------------------------

To control the five types of exceptions defined in IEEE 754 some functions are defined which abstract the interface to the FPU.  The actual implementation can be very different, depending on the underlying hardware or software.

To address the single exception the fenv.h headers defines a number of macros:

FE_INEXACT
     Represents the inexact exception iff the FPU supports this exception.

FE_DIVBYZERO
     Represents the divide by zero exception iff the FPU supports this exception.

FE_UNDERFLOW
     Represents the underflow exception iff the FPU supports this exception.

FE_OVERFLOW
     Represents the overflow exception iff the FPU supports this exception.

FE_INVALID
     Represents the invalid exception iff the FPU supports this exception.

The macro FE_ALL_EXCEPT is the bitwise OR of all exception macros which are supported by the FP implementation.

Each of the supported exception flags can either be set or unset.  The ISO C 9X standard defines functions to set, unset and test the status of the flags.

 -- Function: void feclearexcept (int EXCEPTS)
     This function clears all of the supported exception flags denoted by EXCEPTS in the status word.

To safe the current status of the flags in the status word fenv.h defines the type fexcept_t which can hold all the information. The following function can be used to retrieve the current setting.

 -- Function: void fegetexceptflag (fexcept_t *FLAGP, int EXCEPTS)
     Store in the variable pointed to by FLAGP an implementation-defined value representing the current setting of the exception flags indicated by the parameter EXCEPTS.

To restore the previously saved values one can use this function:

 -- Function: void fesetexceptflag (const fexcept_t *FLAGP, int EXCEPTS)
     Restore from the variable pointed to by FLAGP the setting of the flags for the exceptions denoted by the value of the parameter EXCEPTS.

The last function allows to query the current status of the flags.  The flags can be set either explicitely (using fesetexceptflag or feclearexcept) or by a floating-point operation which happened before.  Since the flags are accumulative, the flags must be explicitely reset using feclearexcept if one wants to test for a certain exceptions raised by a specific piece of code.

 -- Function: int fetestexcept (int EXCEPTS)
     Test whether a subset of the flags indicated by the parameter EXCEPT is currently set.  If yes, a nonzero value is returned which specifies which exceptions are set.  Otherwise the result is zero.

Code which uses the fetestexcept function could look like this:

     {
       double f;
       int raised;
       feclearexcept (FE_ALL_EXCEPT);
       f = compute ();
       raised = fetestexcept (FE_OVERFLOW | FE_INVALID);
       if (raised & FE_OVERFLOW) { /* ... */ }
       if (raised & FE_INVALID) { /* ... */ }
       /* ... */
     }

Please note that the return value of fetestexcept is int but this does not mean that the fexcept_t type is generally representable as an integer.  These are completely independent types.

Controlling the Floating-Point environment
------------------------------------------

It is sometimes necessary so save the complete status of the floating-point unit for a certain time to perform some completely different actions.  Beside the status of the exception flags, the control word for the exceptions and the rounding mode can be saved.

The file fenv.h defines the type fenv_t.  The layout of a variable of this type is implementation defined but the variable is able to contain the complete status information.  To fill a variable of this type one can use this function:

 -- Function: void fegetenv (fenv_t *ENVP)
     Store the current floating-point environment in the object pointed to by ENVP.

Another possibility which is useful in several situations is

 -- Function: int feholdexcept (fenv_t *ENVP)
     Store the current floating-point environment in the object pointed to by ENVP.  Afterwards, all exception flags are cleared and if available a mode is installed which continues on all exceptions and does not cause a trap to occur.  In this case a nonzero value is returned.

     If the floating-point implementation does not support such a non-stop mode, the return value is zero.

The functions which allow a state of the floating-point unit to be restored can take two kinds of arguments:

  * Pointers to fenv_t objects which were initialized previously by a call to fegetenv or feholdexcept.

  * The special macro FE_DFL_ENV which represents the floating-point environment as it was available at program start.

  * Implementation defined macros with names starting with FE_.

     If possible, the GNU C Library defines a macro FE_NOMASK_ENV which represents an environment where no exceptions are masked, so every exception raised causes a trap to occur.  You can test for this macro using #ifdef.

     Some platforms might define other predefined environments.

To set any of the environments there are two functions defined.

 -- Function: void fesetenv (const fenv_t *ENVP)
     Establish the floating-point environment described in the object pointed to by ENVP.  Even if one or more exceptions flags in the restored environment are set no exception is raised.

In some situations the previous status of the exception flags must not simply be discarded and so this function is useful:

 -- Function: void feupdateenv (const fenv_t *ENVP)
     The current status of the floating-point unit is preserved in some automatic storage before the environment described by the object pointed to by ENVP is installed.  Once this is finished all exceptions set in the original environment which is saved in the automatic storage, is raised.

This function can be used to execute a part of the program with an environment which masks all exceptions and before switching back remove unwanted exception and raise the remaining exceptions.

Rounding modes of the Floating-Point Unit
-----------------------------------------

IEEE 754 defines four different rounding modes.  If the rounding mode is supported by the floating-point implementation the corresponding of the following macros is defined:

FE_TONEAREST
     Round to nearest.  This is the default mode and should always be used except when a different mode is explicitely required.  Only rounding to nearest guarantees numeric stability of the computations.

FE_UPWARD
     Round toward +oo.

FE_DOWNWARD
     Round toward -oo.

FE_TOWARDZERO
     Round toward zero.

At any time one of the above four rounding modes is selected.  To get information about the currently selected mode one can use this function:

 -- Function: int fegetround (void)
     Return the currently selected rounding mode, represented by one of the values of the defined rounding mode macros.

To set a specific rounding mode the next function can be used.

 -- Function: int fesetround (int ROUND)
     Change the currently selected rounding mode to the mode described by the parameter ROUND.  If ROUND does not correspond to one of the supported rounding modes nothing is changed.

     The function returns a nonzero value iff the requested rounding mode can be established.  Otherwise zero is returned.

Changing the rounding mode might be necessary for various reasons.  But changing the mode only to round a given number normally is no good idea. The standard defines a set of functions which can be used to round an argument according to some rules and for all of the rounding modes there is a corresponding function.

If a large set of number has to be rounded it might be good to change the rounding mode and to not use the function the library provides.  So the perhaps necessary switching of the rounding mode in the library function can be avoided.  But since not all rounding modes are guaranteed to exist on any platform this possible implementation cannot be portably used.  A default method has to be implemented as well.

Predefined Mathematical Constants
=================================

The header math.h defines a series of mathematical constants if _BSD_SOURCE or a more general feature select macro is defined before including this file.  All values are defined as preprocessor macros starting with M_.  The collection includes:

M_E
     The value is that of the base of the natural logarithm.

M_LOG2E
     The value is computed as the logarithm to base 2 of M_E.

M_LOG10E
     The value is computed as the logarithm to base 10 of M_E.

M_LN2
     The value is computed as the natural logarithm of 2.

M_LN10
     The value is computed as the natural logarithm of 10.

M_PI
     The value is those of the number pi.

M_PI_2
     The value is those of the number pi divided by two.

M_PI_4
     The value is those of the number pi divided by four.

M_1_PI
     The value is the reziprocal of the value of the number pi.

M_2_PI
     The value is two times the reziprocal of the value of the number pi.

M_2_SQRTPI
     The value is two times the reziprocal of the square root of the number pi.

M_SQRT2
     The value is the square root of the value of the number pi.

M_SQRT1_2
     The value is the reziprocal of the square root of the value of the number pi.

All values are defined as long double values unless the compiler does not support this type or __STDC__ is not defined (both is unlikely).  Historically the numbers were double values and some old code still relies on this so you might want to add explicit casts if the extra precision of the long double value is not needed.  One critical case are functions with a variable number of arguments, such as printf.

Note: Some programs use a constant named PI which has the same value as M_PI.  This probably derives from Stroustroup's book about his C++ programming language where this value is used in examples (and perhaps some AT&T headers contain this value).  But due to possible name space problems (PI is a quite frequently used name) this value is not added to math.h.  Every program should use M_PI instead or add on the compiler command line -DPI=M_PI.

Floating-Point Comparison Functions
===================================

The IEEE 754 standards defines a set of functions which allows to compare even those numbers which normally would cause an exception to be raised since they are unordered.  E.g., the expression

     int v = a < 1.0;

would raise an exception if A would be a NaN.  Functions to compare unordered numbers are part of the FORTRAN language for a long time and the extensions in ISO C 9X finally introduce them as well for the C programming language.

All of the operations are implemented as macros which allow their arguments to be of either float, double, or long double type.

 -- Macro: int isgreater (real-floating X, real-floating Y)
     This macro determines whether the argument X is greater than Y.  This is equivalent to (X) > (Y) but no exception is raised if X or Y are unordered.

 -- Macro: int isgreaterequal (real-floating X, real-floating Y)
     This macro determines whether the argument X is greater than or equal to Y.  This is equivalent to (X) >= (Y) but no exception is raised if X or Y are unordered.

 -- Macro: int isless (real-floating X, real-floating Y)
     This macro determines whether the argument X is less than Y. This is equivalent (X) < (Y) but no exception is raised if X or Y are unordered.

 -- Macro: int islessequal (real-floating X, real-floating Y)
     This macro determines whether the argument X is less than or equal to Y.  This is equivalent to (X) <= (Y) but no exception is raised if X or Y are unordered.

 -- Macro: int islessgreater (real-floating X, real-floating Y)
     This macro determines whether the argument X is less or greater than Y.  This is equivalent to (X) < (Y) || (X) > (Y) (except that X and Y are only evaluated once) but no exception is raised if X or Y are unordered.

 -- Macro: int isunordered (real-floating X, real-floating Y)
     This macro determines whether its arguments are unordered.

All the macros are defined in a way to ensure that both arguments are evaluated exactly once and so they can be used exactly like the builtin operators.

On several platform these macros are mapped to efficient instructions the processor understands.  But on machines missing these functions, the macros above might be rather slow.  So it is best to use the builtin operators unless it is necessary to use unordered comparisons.

Note: There are no macros isequal or isunequal. These macros are not necessary since the IEEE 754 standard requires that the comparison for equality and unequality do not throw an exception if one of the arguments is an unordered value.

Is Fast Code or Small Code preferred?
=====================================

If an application uses many floating point function it is often the case that the costs for the function calls itselfs are not neglectable. Modern processor implementation often can execute the operation itself very fast but the call means a disturbance of the control flow.

For this reason the GNU C Library provides optimizations for many of the frequently used math functions.  When the GNU CC is used and the user activates the optimizer several new inline functions and macros get defined.  These new functions and macros have the same names as the library function and so get used instead of the later.  In case of inline functions the compiler will decide whether it is reasonable to use the inline function and this decision is usually correct.

For the generated code this means that no calls to the library functions are necessary.  This increases the speed significantly.  But the drawback is that the code size increases and this increase is not always neglectable.

In cases where the inline functions and macros are not wanted the symbol __NO_MATH_INLINES should be defined before any system header is included.  This will make sure only library functions are used.  Of course it can be determined for each single file in the project whether giving this option is preferred or not.

Trigonometric Functions
=======================

These are the familiar sin, cos, and tan functions. The arguments to all of these functions are in units of radians; recall that pi radians equals 180 degrees.

The math library does define a symbolic constant for pi in math.h (see Mathematical Constants) when BSD compliance is required (see Feature Test Macros).  In case it is not possible to use this predefined macro one easily can define it:

     #define M_PI 3.14159265358979323846264338327

You can also compute the value of pi with the expression acos (-1.0).

 -- Function: double sin (double X)
 -- Function: float sinf (float X)
 -- Function: long double sinl (long double X)
     These functions return the sine of X, where X is given in radians.  The return value is in the range -1 to 1.

 -- Function: double cos (double X)
 -- Function: float cosf (float X)
 -- Function: long double cosl (long double X)
     These functions return the cosine of X, where X is given in radians.  The return value is in the range -1 to 1.

 -- Function: double tan (double X)
 -- Function: float tanf (float X)
 -- Function: long double tanl (long double X)
     These functions return the tangent of X, where X is given in radians.

     The following errno error conditions are defined for this function:

     ERANGE
          Mathematically, the tangent function has singularities at odd multiples of pi/2.  If the argument X is too close to one of these singularities, tan sets errno to ERANGE and returns either positive or negative HUGE_VAL.

In many applications where sin and cos are used, the value for the same argument of both of these functions is used at the same time.  Since the algorithm to compute these values is very similar for both functions there is an additional function which computes both values at the same time.

 -- Function: void sincos (double X, double *SINX, double *COSX)
 -- Function: void sincosf (float X, float *SINX, float *COSX)
 -- Function: void sincosl (long double X, long double *SINX, long double *COSX)
     These functions return the sine of X in *SINX and the cosine of X in *COS, where X is given in radians.  Both values, *SINX and *COSX, are in the range of -1 to 1.

     This function is a GNU extension.  It should be used whenever both sine and cosine are needed but in portable applications there should be a fallback method for systems without this function.

The trigonometric functions are in mathematics not only defined on real numbers.  They can be extended to complex numbers and the ISO C 9X standard introduces these variants in the standard math library.

 -- Function: complex double csin (complex double Z)
 -- Function: complex float csinf (complex float Z)
 -- Function: complex long double csinl (complex long double Z)
     These functions return the complex sine of the complex value in Z. The mathematical definition of the complex sine is

     sin (z) = 1/(2*i) * (exp (z*i) - exp (-z*i)).

 -- Function: complex double ccos (complex double Z)
 -- Function: complex float ccosf (complex float Z)
 -- Function: complex long double ccosl (complex long double Z)
     These functions return the complex cosine of the complex value in Z. The mathematical definition of the complex cosine is

     cos (z) = 1/2 * (exp (z*i) + exp (-z*i))

 -- Function: complex double ctan (complex double Z)
 -- Function: complex float ctanf (complex float Z)
 -- Function: complex long double ctanl (complex long double Z)
     These functions return the complex tangent of the complex value in Z. The mathematical definition of the complex tangent is

     tan (z) = 1/i * (exp (z*i) - exp (-z*i)) / (exp (z*i) + exp (-z*i))

Inverse Trigonometric Functions
===============================

These are the usual arc sine, arc cosine and arc tangent functions, which are the inverses of the sine, cosine and tangent functions, respectively.

 -- Function: double asin (double X)
 -- Function: float asinf (float X)
 -- Function: long double asinl (long double X)
     These functions compute the arc sine of X---that is, the value whose sine is X.  The value is in units of radians.  Mathematically, there are infinitely many such values; the one actually returned is the one between -pi/2 and pi/2 (inclusive).

     asin fails, and sets errno to EDOM, if X is out of range.  The arc sine function is defined mathematically only over the domain -1 to 1.

 -- Function: double acos (double X)
 -- Function: float acosf (float X)
 -- Function: long double acosl (long double X)
     These functions compute the arc cosine of X---that is, the value whose cosine is X.  The value is in units of radians. Mathematically, there are infinitely many such values; the one actually returned is the one between 0 and pi (inclusive).

     acos fails, and sets errno to EDOM, if X is out of range.  The arc cosine function is defined mathematically only over the domain -1 to 1.

 -- Function: double atan (double X)
 -- Function: float atanf (float X)
 -- Function: long double atanl (long double X)
     These functions compute the arc tangent of X---that is, the value whose tangent is X.  The value is in units of radians. Mathematically, there are infinitely many such values; the one actually returned is the one between -pi/2 and pi/2 (inclusive).

 -- Function: double atan2 (double Y, double X)
 -- Function: float atan2f (float Y, float X)
 -- Function: long double atan2l (long double Y, long double X)
     This is the two argument arc tangent function.  It is similar to computing the arc tangent of Y/X, except that the signs of both arguments are used to determine the quadrant of the result, and X is permitted to be zero.  The return value is given in radians and is in the range -pi to pi, inclusive.

     If X and Y are coordinates of a point in the plane, atan2 returns the signed angle between the line from the origin to that point and the x-axis.  Thus, atan2 is useful for converting Cartesian coordinates to polar coordinates.  (To compute the radial coordinate, use hypot; see Exponents and Logarithms.)

     The function atan2 sets errno to EDOM if both X and Y are zero; the return value is not defined in this case.

The inverse trigonometric functions also exist is separate versions which are usable with complex numbers.

 -- Function: complex double casin (complex double Z)
 -- Function: complex float casinf (complex float Z)
 -- Function: complex long double casinl (complex long double Z)
     These functions compute the complex arc sine of Z---that is, the value whose sine is Z.  The value is in units of radians.

     Unlike the real version of the arc sine function casin has no limitation on the argument Z.

 -- Function: complex double cacos (complex double Z)
 -- Function: complex float cacosf (complex float Z)
 -- Function: complex long double cacosl (complex long double Z)
     These functions compute the complex arc cosine of Z---that is, the value whose cosine is Z.  The value is in units of radians.

     Unlike the real version of the arc cosine function cacos has no limitation on the argument Z.

 -- Function: complex double catan (complex double Z)
 -- Function: complex float catanf (complex float Z)
 -- Function: complex long double catanl (complex long double Z)
     These functions compute the complex arc tangent of Z---that is, the value whose tangent is Z.  The value is in units of radians.

Exponentiation and Logarithms
=============================

 -- Function: double exp (double X)
 -- Function: float expf (float X)
 -- Function: long double expl (long double X)
     These functions return the value of e (the base of natural logarithms) raised to power X.

     The function fails, and sets errno to ERANGE, if the magnitude of the result is too large to be representable.

 -- Function: double exp10 (double X)
 -- Function: float exp10f (float X)
 -- Function: long double exp10l (long double X)
     These functions return the value of 10 raised to the power X. Mathematically, exp10 (x) is the same as exp (x * log (10)).

     The function fails, and sets errno to ERANGE, if the magnitude of the result is too large to be representable.

 -- Function: double exp2 (double X)
 -- Function: float exp2f (float X)
 -- Function: long double exp2l (long double X)
     These functions return the value of 2 raised to the power X. Mathematically, exp2 (x) is the same as exp (x * log (2)).

     The function fails, and sets errno to ERANGE, if the magnitude of the result is too large to be representable.

 -- Function: double log (double X)
 -- Function: float logf (float X)
 -- Function: long double logl (long double X)
     These functions return the natural logarithm of X.  exp (log (X)) equals X, exactly in mathematics and approximately in C.

     The following errno error conditions are defined for this function:

     EDOM
          The argument X is negative.  The log function is defined mathematically to return a real result only on positive arguments.

     ERANGE
          The argument is zero.  The log of zero is not defined.

 -- Function: double log10 (double X)
 -- Function: float log10f (float X)
 -- Function: long double log10l (long double X)
     These functions return the base-10 logarithm of X.  Except for the different base, it is similar to the log function.  In fact, log10 (X) equals log (X) / log (10).

 -- Function: double log2 (double X)
 -- Function: float log2f (float X)
 -- Function: long double log2l (long double X)
     These functions return the base-2 logarithm of X.  Except for the different base, it is similar to the log function.  In fact, log2 (X) equals log (X) / log (2).

 -- Function: double logb (double X)
 -- Function: float logbf (float X)
 -- Function: long double logbl (long double X)
     These functions extract the exponent of X and return it as a signed integer value.  If X is zero, a range error may occur.

     A special case are subnormal numbers (if supported by the floating-point format).  The exponent returned is not the actual value from X. Instead the number is first normalized as if the range of the exponent field is large enough.

 -- Function: int ilogb (double X)
 -- Function: int ilogbf (float X)
 -- Function: int ilogbl (long double X)
     These functions are equivalent to the corresponding logb functions except that the values are returned as signed integer values. Since integer values cannot represent infinity and NaN, there are some special symbols defined to help detect these situations.

     ilogb returns FP_ILOGB0 if X is 0 and it returns FP_ILOGBNAN if X is NaN.  These values are system specific and no fixed value is assigned.  More concrete, these values might even have the same value.  So a piece of code handling the result of ilogb could look like this:

          i = ilogb (f);
          if (i == FP_ILOGB0 || i == FP_ILOGBNAN)
            {
              if (isnan (f))
                {
                  /* Handle NaN.  */
                }
              else if (f  == 0.0)
                {
                  /* Handle 0.0.  */
                }
              else
                {
                  /* Some other value with large exponent,
                     perhaps +Inf.  */
                }
            }

 -- Function: double pow (double BASE, double POWER)
 -- Function: float powf (float BASE, float POWER)
 -- Function: long double powl (long double BASE, long double POWER)
     These are general exponentiation functions, returning BASE raised to POWER.

     The following errno error conditions are defined for this function:

     EDOM
          The argument BASE is negative and POWER is not an integral value.  Mathematically, the result would be a complex number in this case.

     ERANGE
          An underflow or overflow condition was detected in the result.

 -- Function: double sqrt (double X)
 -- Function: float sqrtf (float X)
 -- Function: long double sqrtl (long double X)
     These functions return the nonnegative square root of X.

     The sqrt function fails, and sets errno to EDOM, if X is negative.  Mathematically, the square root would be a complex number.

 -- Function: double cbrt (double X)
 -- Function: float cbrtf (float X)
 -- Function: long double cbrtl (long double X)
     These functions return the cube root of X.  They cannot fail; every representable real value has a representable real cube root.

 -- Function: double hypot (double X, double Y)
 -- Function: float hypotf (float X, float Y)
 -- Function: long double hypotl (long double X, long double Y)
     These functions return sqrt (X*X + Y*Y).  (This is the length of the hypotenuse of a right triangle with sides of length X and Y, or the distance of the point (X, Y) from the origin.)  Using this function instead of the direct formula is highly appreciated since the error is much smaller.  See also the function cabs in Absolute Value.

 -- Function: double expm1 (double X)
 -- Function: float expm1f (float X)
 -- Function: long double expm1l (long double X)
     These functions return a value equivalent to exp (X) - 1. It is computed in a way that is accurate even if the value of X is near zero---a case where exp (X) - 1 would be inaccurate due to subtraction of two numbers that are nearly equal.

 -- Function: double log1p (double X)
 -- Function: float log1pf (float X)
 -- Function: long double log1pl (long double X)
     This function returns a value equivalent to log (1 + X). It is computed in a way that is accurate even if the value of X is near zero.

ISO C 9X defines variants of some of the exponentiation and logarithm functions.  As for the other functions handling complex numbers these functions are perhaps better optimized and provide better error checking than a direct use of the formulas of the mathematical definition.

 -- Function: complex double cexp (complex double Z)
 -- Function: complex float cexpf (complex float Z)
 -- Function: complex long double cexpl (complex long double Z)
     These functions return the value of e (the base of natural logarithms) raised to power of the complex value Z.

     Mathematically this corresponds to the value

     exp (z) = exp (creal (z)) * (cos (cimag (z)) + I * sin (cimag (z)))

 -- Function: complex double clog (complex double Z)
 -- Function: complex float clogf (complex float Z)
 -- Function: complex long double clogl (complex long double Z)
     These functions return the natural logarithm of the complex value Z.  Unlike the real value version log and its variants, clog has no limit for the range of its argument Z.

     Mathematically this corresponds to the value

     log (z) = log (cabs (z)) + I * carg (z)

 -- Function: complex double clog10 (complex double Z)
 -- Function: complex float clog10f (complex float Z)
 -- Function: complex long double clog10l (complex long double Z)
     These functions return the base 10 logarithm of the complex value Z.  Unlike the real value version log and its variants, clog has no limit for the range of its argument Z.

     Mathematically this corresponds to the value

     log (z) = log10 (cabs (z)) + I * carg (z)

     This function is a GNU extension.

 -- Function: complex double csqrt (complex double Z)
 -- Function: complex float csqrtf (complex float Z)
 -- Function: complex long double csqrtl (complex long double Z)
     These functions return the complex root of the argument Z.  Unlike the sqrt function these functions do not have any restriction on the value of the argument.

 -- Function: complex double cpow (complex double BASE, complex double POWER)
 -- Function: complex float cpowf (complex float BASE, complex float POWER)
 -- Function: complex long double cpowl (complex long double BASE, complex long double POWER)
     These functions return the complex value BASE raised to the power of POWER.  This is computed as

     cpow (x, y) = cexp (y * clog (x))

Hyperbolic Functions
====================

The functions in this section are related to the exponential functions; see Exponents and Logarithms.

 -- Function: double sinh (double X)
 -- Function: float sinhf (float X)
 -- Function: long double sinhl (long double X)
     These functions return the hyperbolic sine of X, defined mathematically as (exp (X) - exp (-X)) / 2.  The function fails, and sets errno to ERANGE, if the value of X is too large; that is, if overflow occurs.

 -- Function: double cosh (double X)
 -- Function: float coshf (float X)
 -- Function: long double coshl (long double X)
     These function return the hyperbolic cosine of X, defined mathematically as (exp (X) + exp (-X)) / 2. The function fails, and sets errno to ERANGE, if the value of X is too large; that is, if overflow occurs.

 -- Function: double tanh (double X)
 -- Function: float tanhf (float X)
 -- Function: long double tanhl (long double X)
     These functions return the hyperbolic tangent of X, whose mathematical definition is sinh (X) / cosh (X).

There are counterparts for these hyperbolic functions which work with complex valued arguments.  They should always be used instead of the obvious mathematical formula since the implementations in the math library are optimized for accuracy and speed.

 -- Function: complex double csinh (complex double Z)
 -- Function: complex float csinhf (complex float Z)
 -- Function: complex long double csinhl (complex long double Z)
     These functions return the complex hyperbolic sine of Z, defined mathematically as (exp (Z) - exp (-Z)) / 2.  The function fails, and sets errno to ERANGE, if the value of result is too large.

 -- Function: complex double ccosh (complex double Z)
 -- Function: complex float ccoshf (complex float Z)
 -- Function: complex long double ccoshl (complex long double Z)
     These functions return the complex hyperbolic cosine of Z, defined mathematically as (exp (Z) + exp (-Z)) / 2.  The function fails, and sets errno to ERANGE, if the value of result is too large.

 -- Function: complex double ctanh (complex double Z)
 -- Function: complex float ctanhf (complex float Z)
 -- Function: complex long double ctanhl (complex long double Z)
     These functions return the complex hyperbolic tangent of Z, whose mathematical definition is csinh (Z) / ccosh (Z).

 -- Function: double asinh (double X)
 -- Function: float asinhf (float X)
 -- Function: long double asinhl (long double X)
     These functions return the inverse hyperbolic sine of X---the value whose hyperbolic sine is X.

 -- Function: double acosh (double X)
 -- Function: float acoshf (float X)
 -- Function: long double acoshl (long double X)
     These functions return the inverse hyperbolic cosine of X---the value whose hyperbolic cosine is X.  If X is less than 1, acosh returns HUGE_VAL.

 -- Function: double atanh (double X)
 -- Function: float atanhf (float X)
 -- Function: long double atanhl (long double X)
     These functions return the inverse hyperbolic tangent of X---the value whose hyperbolic tangent is X.  If the absolute value of X is greater than or equal to 1, atanh returns HUGE_VAL.

 -- Function: complex double casinh (complex double Z)
 -- Function: complex float casinhf (complex float Z)
 -- Function: complex long double casinhl (complex long double Z)
     These functions return the inverse complex hyperbolic sine of Z---the value whose complex hyperbolic sine is Z.

 -- Function: complex double cacosh (complex double Z)
 -- Function: complex float cacoshf (complex float Z)
 -- Function: complex long double cacoshl (complex long double Z)
     These functions return the inverse complex hyperbolic cosine of Z---the value whose complex hyperbolic cosine is Z.  Unlike the real valued function acosh there is not limit for the range of the argument.

 -- Function: complex double catanh (complex double Z)
 -- Function: complex float catanhf (complex float Z)
 -- Function: complex long double catanhl (complex long double Z)
     These functions return the inverse complex hyperbolic tangent of Z---the value whose complex hyperbolic tangent is Z.  Unlike the real valued function atanh there is not limit for the range of the argument.

Pseudo-Random Numbers
=====================

This section describes the GNU facilities for generating a series of pseudo-random numbers.  The numbers generated are not truly random; typically, they form a sequence that repeats periodically, with a period so large that you can ignore it for ordinary purposes.  The random number generator works by remembering at all times a seed value which it uses to compute the next random number and also to compute a new seed.

Although the generated numbers look unpredictable within one run of a program, the sequence of numbers is exactly the same from one run to the next.  This is because the initial seed is always the same.  This is convenient when you are debugging a program, but it is unhelpful if you want the program to behave unpredictably.  If you want truly random numbers, not just pseudo-random, specify a seed based on the current time.

You can get repeatable sequences of numbers on a particular machine type by specifying the same initial seed value for the random number generator.  There is no standard meaning for a particular seed value; the same seed, used in different C libraries or on different CPU types, will give you different random numbers.

The GNU library supports the standard ISO C random number functions plus two other sets derived from BSD and SVID.  We recommend you use the standard ones, rand and srand if only a small number of random bits are required.  The SVID functions provide an interface which allows better random number generator algorithms and they return up to 48 random bits in one calls and they also return random floating-point numbers if wanted.  The SVID function might not be available on some BSD derived systems but since they are required in the XPG they are available on all Unix-conformant systems.

ISO C Random Number Functions
-----------------------------

This section describes the random number functions that are part of the ISO C standard.

To use these facilities, you should include the header file stdlib.h in your program.

 -- Macro: int RAND_MAX
     The value of this macro is an integer constant expression that represents the maximum possible value returned by the rand function.  In the GNU library, it is 037777777, which is the largest signed integer representable in 32 bits.  In other libraries, it may be as low as 32767.

 -- Function: int rand (void)
     The rand function returns the next pseudo-random number in the series.  The value is in the range from 0 to RAND_MAX.

 -- Function: void srand (unsigned int SEED)
     This function establishes SEED as the seed for a new series of pseudo-random numbers.  If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.

     To produce truly random numbers (not just pseudo-random), do srand (time (0)).

A completely broken interface was designed by the POSIX.1 committee to support reproducible random numbers in multi-threaded programs.

 -- Function: int rand_r (unsigned int *SEED)
     This function returns a random number in the range 0 to RAND_MAX just as rand does.  But this function does not keep an internal state for the RNG.  Instead the unsigned int variable pointed to by the argument SEED is the only state.  Before the value is returned the state will be updated so that the next call will return a new number.

     I.e., the state of the RNG can only have as much bits as the type unsigned int has.  This is far too few to provide a good RNG. This interface is broken by design.

     If the program requires reproducible random numbers in multi-threaded programs the reentrant SVID functions are probably a better choice.  But these functions are GNU extensions and therefore rand_r, as being standardized in POSIX.1, should always be kept as a default method.

BSD Random Number Functions
---------------------------

This section describes a set of random number generation functions that are derived from BSD.  There is no advantage to using these functions with the GNU C library; we support them for BSD compatibility only.

The prototypes for these functions are in stdlib.h.

 -- Function: int32_t random (void)
     This function returns the next pseudo-random number in the sequence. The range of values returned is from 0 to RAND_MAX.

     Please note: Historically this function returned a long int value.  But with the appearance of 64bit machines this could lead to severe compatibility problems and therefore the type now explicitly limits the return value to 32bit.

 -- Function: void srandom (unsigned int SEED)
     The srandom function sets the seed for the current random number state based on the integer SEED.  If you supply a SEED value of 1, this will cause random to reproduce the default set of random numbers.

     To produce truly random numbers (not just pseudo-random), do srandom (time (0)).

 -- Function: void * initstate (unsigned int SEED, void *STATE, size_t SIZE)
     The initstate function is used to initialize the random number generator state.  The argument STATE is an array of SIZE bytes, used to hold the state information.  The size must be at least 8 bytes, and optimal sizes are 8, 16, 32, 64, 128, and 256.  The bigger the STATE array, the better.

     The return value is the previous value of the state information array. You can use this value later as an argument to setstate to restore that state.

 -- Function: void * setstate (void *STATE)
     The setstate function restores the random number state information STATE.  The argument must have been the result of a previous call to INITSTATE or SETSTATE.

     The return value is the previous value of the state information array. You can use this value later as an argument to setstate to restore that state.

SVID Random Number Function
---------------------------

The C library on SVID systems contains yet another kind of random number generator functions.  They use a state of 48 bits of data.  The user can choose among a collection of functions which all return the random bits in different forms.

Generally there are two kinds of functions: those which use a state of the random number generator which is shared among several functions and by all threads of the process.  The second group of functions require the user to handle the state.

All functions have in common that they use the same congruential formula with the same constants.  The formula is

     Y = (a * X + c) mod m

where X is the state of the generator at the beginning and Y the state at the end.  a and c are constants determining the way the generator work.  By default they are

     a = 0x5DEECE66D = 25214903917
     c = 0xb = 11

but they can also be changed by the user.  m is of course 2^48 since the state consists of a 48 bit array.

 -- Function: double drand48 (void)
     This function returns a double value in the range of 0.0 to 1.0 (exclusive).  The random bits are determined by the global state of the random number generator in the C library.

     Since the double type according to IEEE 754 has a 52 bit mantissa this means 4 bits are not initialized by the random number generator.  These are (of course) chosen to be the least significant bits and they are initialized to 0.

 -- Function: double erand48 (unsigned short int XSUBI[3])
     This function returns a double value in the range of 0.0 to 1.0 (exclusive), similar to drand48.  The argument is an array describing the state of the random number generator.

     This function can be called subsequently since it updates the array to guarantee random numbers.  The array should have been initialized before using to get reproducible results.

 -- Function: long int lrand48 (void)
     The lrand48 functions return an integer value in the range of 0 to 2^31 (exclusive).  Even if the size of the long int type can take more than 32 bits no higher numbers are returned. The random bits are determined by the global state of the random number generator in the C library.

 -- Function: long int nrand48 (unsigned short int XSUBI[3])
     This function is similar to the lrand48 function in that it returns a number in the range of 0 to 2^31 (exclusive) but the state of the random number generator used to produce the random bits is determined by the array provided as the parameter to the function.

     The numbers in the array are afterwards updated so that subsequent calls to this function yield to different results (as it is expected by a random number generator).  The array should have been initialized before the first call to get reproducible results.

 -- Function: long int mrand48 (void)
     The mrand48 function is similar to lrand48.  The only difference is that the numbers returned are in the range -2^31 to 2^31 (exclusive).

 -- Function: long int jrand48 (unsigned short int XSUBI[3])
     The jrand48 function is similar to nrand48.  The only difference is that the numbers returned are in the range -2^31 to 2^31 (exclusive).  For the xsubi parameter the same requirements are necessary.

The internal state of the random number generator can be initialized in several ways.  The functions differ in the completeness of the information provided.

 -- Function: void srand48 (long int SEEDVAL))
     The srand48 function sets the most significant 32 bits of the state internal state of the random number generator to the least significant 32 bits of the SEEDVAL parameter.  The lower 16 bits are initialized to the value 0x330E.  Even if the long int type contains more the 32 bits only the lower 32 bits are used.

     Due to this limitation the initialization of the state using this function of not very useful.  But it makes it easy to use a construct like srand48 (time (0)).

     A side-effect of this function is that the values a and c from the internal state, which are used in the congruential formula, are reset to the default values given above.  This is of importance once the user called the lcong48 function (see below).

 -- Function: unsigned short int * seed48 (unsigned short int SEED16V[3])
     The seed48 function initializes all 48 bits of the state of the internal random number generator from the content of the parameter SEED16V.  Here the lower 16 bits of the first element of SEE16V initialize the least significant 16 bits of the internal state, the lower 16 bits of SEED16V[1] initialize the mid-order 16 bits of the state and the 16 lower bits of SEED16V[2] initialize the most significant 16 bits of the state.

     Unlike srand48 this function lets the user initialize all 48 bits of the state.

     The value returned by seed48 is a pointer to an array containing the values of the internal state before the change.  This might be useful to restart the random number generator at a certain state. Otherwise, the value can simply be ignored.

     As for srand48, the values a and c from the congruential formula are reset to the default values.

There is one more function to initialize the random number generator which allows to specify even more information by allowing to change the parameters in the congruential formula.

 -- Function: void lcong48 (unsigned short int PARAM[7])
     The lcong48 function allows the user to change the complete state of the random number generator.  Unlike srand48 and seed48, this function also changes the constants in the congruential formula.

     From the seven elements in the array PARAM the least significant 16 bits of the entries PARAM[0] to PARAM[2] determine the the initial state, the least 16 bits of PARAM[3] to PARAM[5] determine the 48 bit constant a and PARAM[6] determines the 16 bit value c.

All the above functions have in common that they use the global parameters for the congruential formula.  In multi-threaded programs it might sometimes be useful to have different parameters in different threads.  For this reason all the above functions have a counterpart which works on a description of the random number generator in the user-supplied buffer instead of the global state.

Please note that it is no problem if several threads use the global state if all threads use the functions which take a pointer to an array containing the state.  The random numbers are computed following the same loop but if the state in the array is different all threads will get an individual random number generator.

The user supplied buffer must be of type struct drand48_data. This type should be regarded as opaque and no member should be used directly.

 -- Function: int drand48_r (struct drand48_data *BUFFER, double *RESULT)
     This function is equivalent to the drand48 function with the difference it does not modify the global random number generator parameters but instead the parameters is the buffer supplied by the buffer through the pointer BUFFER.  The random number is return in the variable pointed to by RESULT.

     The return value of the function indicate whether the call succeeded. If the value is less than 0 an error occurred and ERRNO is set to indicate the problem.

     This function is a GNU extension and should not be used in portable programs.

 -- Function: int erand48_r (unsigned short int XSUBI[3], struct drand48_data *BUFFER, double *RESULT)
     The erand48_r function works like the erand48 and it takes an argument BUFFER which describes the random number generator. The state of the random number generator is taken from the xsubi array, the parameters for the congruential formula from the global random number generator data.  The random number is return in the variable pointed to by RESULT.

     The return value is non-negative is the call succeeded.

     This function is a GNU extension and should not be used in portable programs.

 -- Function: int lrand48_r (struct drand48_data *BUFFER, double *RESULT)
     This function is similar to lrand48 and it takes a pointer to a buffer describing the state of the random number generator as a parameter just like drand48.

     If the return value of the function is non-negative the variable pointed to by RESULT contains the result.  Otherwise an error occurred.

     This function is a GNU extension and should not be used in portable programs.

 -- Function: int nrand48_r (unsigned short int XSUBI[3], struct drand48_data *BUFFER, long int *RESULT)
     The nrand48_r function works like nrand48 in that it produces a random number in range 0 to 2^31.  But instead of using the global parameters for the congruential formula it uses the information from the buffer pointed to by BUFFER.  The state is described by the values in XSUBI.

     If the return value is non-negative the variable pointed to by RESULT contains the result.

     This function is a GNU extension and should not be used in portable programs.

 -- Function: int mrand48_r (struct drand48_data *BUFFER, double *RESULT)
     This function is similar to mrand48 but as the other reentrant function it uses the random number generator described by the value in the buffer pointed to by BUFFER.

     If the return value is non-negative the variable pointed to by RESULT contains the result.

     This function is a GNU extension and should not be used in portable programs.

 -- Function: int jrand48_r (unsigned short int XSUBI[3], struct drand48_data *BUFFER, long int *RESULT)
     The jrand48_r function is similar to jrand48.  But as the other reentrant functions of this function family it uses the congruential formula parameters from the buffer pointed to by BUFFER.

     If the return value is non-negative the variable pointed to by RESULT contains the result.

     This function is a GNU extension and should not be used in portable programs.

Before any of the above functions should be used the buffer of type struct drand48_data should initialized.  The easiest way is to fill the whole buffer with null bytes, e.g., using

     memset (buffer, '\0', sizeof (struct drand48_data));

Using any of the reentrant functions of this family now will automatically initialize the random number generator to the default values for the state and the parameters of the congruential formula.

The other possibility is too use any of the functions which explicitely initialize the buffer.  Though it might be obvious how to initialize the buffer from the data given as parameter from the function it is highly recommended to use these functions since the result might not always be what you expect.

 -- Function: int srand48_r (long int SEEDVAL, struct drand48_data *BUFFER)
     The description of the random number generator represented by the information in BUFFER is initialized similar to what the function srand48 does.  The state is initialized from the parameter SEEDVAL and the parameters for the congruential formula are initialized to the default values.

     If the return value is non-negative the function call succeeded.

     This function is a GNU extension and should not be used in portable programs.

 -- Function: int seed48_r (unsigned short int SEED16V[3], struct drand48_data *BUFFER)
     This function is similar to srand48_r but like seed48 it initializes all 48 bits of the state from the parameter SEED16V.

     If the return value is non-negative the function call succeeded.  It does not return a pointer to the previous state of the random number generator like the seed48 function does.  if the user wants to preserve the state for a later rerun s/he can copy the whole buffer pointed to by BUFFER.

     This function is a GNU extension and should not be used in portable programs.

 -- Function: int lcong48_r (unsigned short int PARAM[7], struct drand48_data *BUFFER)
     This function initializes all aspects of the random number generator described in BUFFER by the data in PARAM.  Here it is especially true the function does more than just copying the contents of PARAM of BUFFER.  Some more actions are required and therefore it is important to use this function and not initialized the random number generator directly.

     If the return value is non-negative the function call succeeded.

     This function is a GNU extension and should not be used in portable programs.