Go to the first, previous, next, last section, table of contents.
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'. The complex-valued functions are defined in `complex.h'.
All mathematical functions which take a floating-point argument
have three variants, one each for double
, float
, and
long double
arguments. The double
versions are mostly
defined in ISO C 89. The float
and long double
versions are from the numeric extensions to C included in ISO C 9X.
Which of the three versions of a function should be used depends on the
situation. For most calculations, the float
functions are the
fastest. On the other hand, the long double
functions have the
highest precision. double
is somewhere in between. It is
usually wise to pick the narrowest type that can accomodate your data.
Not all machines have a distinct long double
type; it may be the
same as double
.
The header `math.h' defines several useful mathematical constants.
All values are defined as preprocessor macros starting with M_
.
The values provided are:
M_E
M_LOG2E
2
of M_E
.
M_LOG10E
10
of M_E
.
M_LN2
2
.
M_LN10
10
.
M_PI
M_PI_2
M_PI_4
M_1_PI
M_2_PI
M_2_SQRTPI
M_SQRT2
M_SQRT1_2
These constants come from the Unix98 standard and were also available in
4.4BSD; therefore, they are only defined if _BSD_SOURCE
or
_XOPEN_SOURCE=500
, or a more general feature select macro, is
defined. The default set of features includes these constants.
See section Feature Test Macros.
All values are of type double
. As an extension, the GNU C
library also defines these constants with type long double
. The
long double
macros have a lowercase `l' appended to their
names: M_El
, M_PIl
, and so forth. These are only
available if _GNU_SOURCE
is defined.
Note: Some programs use a constant named PI
which has the
same value as M_PI
. This constant is not standard; it may have
appeared in some old AT&T headers, and is mentioned in Stroustrup's book
on C++. It infringes on the user's name space, so the GNU C library
does not define it. Fixing programs written to expect it is simple:
replace PI
with M_PI
throughout, or put `-DPI=M_PI'
on the compiler command line.
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 normally defines M_PI
to a double
approximation of pi. If strict ISO and/or POSIX compliance
are requested this constant is not defined, but you can easily define it
yourself:
#define M_PI 3.14159265358979323846264338327
You can also compute the value of pi with the expression acos
(-1.0)
.
-1
to 1
.
-1
to 1
.
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
will signal overflow.
In many applications where sin
and cos
are used, the sine
and cosine of the same angle are needed at the same time. It is more
efficient to compute them simultaneously, so the library provides a
function to do that.
*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. Portable programs should be prepared to cope with its absence.
ISO C 9x defines variants of the trig functions which work on complex numbers. The GNU C library provides these functions, but they are only useful if your compiler supports the new complex types defined by the standard. (As of this writing GCC supports complex numbers, but there are bugs in the implementation.)
The complex tangent has poles at pi/2 + 2n, where n is an
integer. ctan
may signal overflow if z is too close to a
pole.
These are the usual arc sine, arc cosine and arc tangent functions, which are the inverses of the sine, cosine and tangent functions, respectively.
-pi/2
and pi/2
(inclusive).
The arc sine function is defined mathematically only
over the domain -1
to 1
. If x is outside the
domain, asin
signals a domain error.
0
and pi
(inclusive).
The arc cosine function is defined mathematically only
over the domain -1
to 1
. If x is outside the
domain, acos
signals a domain error.
-pi/2
and pi/2
(inclusive).
-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 section Exponentiation and Logarithms.)
If both x and y are zero, atan2
returns zero.
ISO C 9x defines complex versions of the inverse trig functions.
Unlike the real-valued functions, casin
is defined for all
values of z.
Unlike the real-valued functions, cacos
is defined for all
values of z.
e
(the base of natural logarithms) raised
to the power x.
If the magnitude of the result is too large to be representable,
exp
signals overflow.
2
raised to the power x.
Mathematically, exp2 (x)
is the same as exp (x * log (2))
.
10
raised to the power x.
Mathematically, exp10 (x)
is the same as exp (x * log (10))
.
These functions are GNU extensions. The name exp10
is
preferred, since it is analogous to exp
and exp2
.
exp (log
(x))
equals x, exactly in mathematics and approximately in
C.
If x is negative, log
signals a domain error. If x
is zero, it returns negative infinity; if x is too close to zero,
it may signal overflow.
log10 (x)
equals log (x) / log (10)
.
log2 (x)
equals log (x) / log (2)
.
FLT_RADIX
is two, logb
is equal
to floor (log2 (x))
, except it's probably faster.
If x is denormalized, logb
returns the exponent x
would have if it were normalized. If x is infinity (positive or
negative), logb
returns @infinity{}. If x is zero,
logb
returns @infinity{}. It does not signal.
logb
functions except that they return signed integer values.
Since integers cannot represent infinity and NaN, ilogb
instead
returns an integer that can't be the exponent of a normal floating-point
number. `math.h' defines constants so you can check for this.
ilogb
returns this value if its argument is 0
. The
numeric value is either INT_MIN
or -INT_MAX
.
This macro is defined in ISO C 9X.
ilogb
returns this value if its argument is NaN
. The
numeric value is either INT_MIN
or INT_MAX
.
This macro is defined in ISO C 9X.
These values are system specific. They might even be the same. The
proper way to test the result of ilogb
is as follows:
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. */ } }
Mathematically, pow
would return a complex number when base
is negative and power is not an integral value. pow
can't
do that, so instead it signals a domain error. pow
may also
underflow or overflow the destination type.
If x is negative, sqrt
signals a domain error.
Mathematically, it should return a complex number.
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 wise, since the error is
much smaller. See also the function cabs
in section Absolute Value.
exp (x) - 1
.
They are computed in a way that is accurate even if x is
near zero--a case where exp (x) - 1
would be inaccurate due
to subtraction of two numbers that are nearly equal.
log (1 + x)
.
They are computed in a way that is accurate even if x is
near zero.
ISO C 9X defines complex variants of some of the exponentiation and logarithm functions.
e
(the base of natural
logarithms) raised to the power of z.
Mathematically this corresponds to the value
clog
has a pole at 0, and will signal overflow if z equals
or is very close to 0. It is well-defined for all other values of
z.
These functions are GNU extensions.
cexp (y * clog (x))
The functions in this section are related to the exponential functions; see section Exponentiation and Logarithms.
(exp (x) - exp (-x)) / 2
. They
may signal overflow if x is too large.
(exp (x) + exp (-x)) / 2
.
They may signal overflow if x is too large.
sinh (x) / cosh (x)
.
They may signal overflow if x is too large.
There are counterparts for the hyperbolic functions which take complex arguments.
(exp (z) - exp (-z)) / 2
.
(exp (z) + exp (-z)) / 2
.
csinh (z) / ccosh (z)
.
1
, acosh
signals a domain error.
1
, atanh
signals a domain error;
if it is equal to 1, atanh
returns infinity.
These are some more exotic mathematical functions, which are sometimes useful. Currently they only have real-valued versions.
erf
returns the error function of x. The error
function is defined as
@ifnottex
erf (x) = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt
erfc
returns 1.0 - erf(x)
, but computed in a
fashion that avoids round-off error when x is large.
lgamma
returns the natural logarithm of the absolute value of
the gamma function of x. The gamma function is defined as
@ifnottex
gamma (x) = integral from 0 to @infinity{} of t^(x-1) e^-t dt
The sign of the gamma function is stored in the global variable
signgam, which is declared in `math.h'. It is 1
if
the intermediate result was positive or zero, and, -1
if it was
negative.
To compute the real gamma function you can use the tgamma
function or you can compute the values as follows:
lgam = lgamma(x); gam = signgam*exp(lgam);
The gamma function has singularities at the nonpositive integers.
lgamma
will raise the zero divide exception if evaluated at a
singularity.
lgamma_r
is just like lgamma
, but it stores the sign of
the intermediate result in the variable pointed to by signp
instead of in the signgam global.
lgamma
etc. It is better to use lgamma
since for one the
name reflects better the actual computation and lgamma
is also
standardized in ISO C 9x while gamma
is not.
tgamma
applies the gamma function to x. The gamma
function is defined as
@ifnottex
gamma (x) = integral from 0 to @infinity{} of t^(x-1) e^-t dt
This function was introduced in ISO C 9x.
j0
returns the Bessel function of the first kind of order 0 of
x. It may signal underflow if x is too large.
j1
returns the Bessel function of the first kind of order 1 of
x. It may signal underflow if x is too large.
jn
returns the Bessel function of the first kind of order
n of x. It may signal underflow if x is too large.
y0
returns the Bessel function of the second kind of order 0 of
x. It may signal underflow if x is too large. If x
is negative, y0
signals a domain error; if it is zero,
y0
signals overflow and returns -@infinity.
y1
returns the Bessel function of the second kind of order 1 of
x. It may signal underflow if x is too large. If x
is negative, y1
signals a domain error; if it is zero,
y1
signals overflow and returns -@infinity.
yn
returns the Bessel function of the second kind of order n of
x. It may signal underflow if x is too large. If x
is negative, yn
signals a domain error; if it is zero,
yn
signals overflow and returns -@infinity.
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 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 a different pseudo-random series each time your program runs, you must specify a different seed each time. For ordinary purposes, basing the seed on the current time works well.
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. The BSD and ISO C
functions provide identical, somewhat limited functionality. If only a
small number of random bits are required, we recommend you use the
ISO C interface, rand
and srand
. The SVID functions
provide a more flexible interface, which allows better random number
generator algorithms, provides more random bits (up to 48) per call, and
can provide random floating-point numbers. These functions are required
by the XPG standard and therefore will be present in all modern Unix
systems.
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.
rand
function can return. In the GNU library, it is
2147483647
, which is the largest signed integer representable in
32 bits. In other libraries, it may be as low as 32767
.
rand
function returns the next pseudo-random number in the
series. The value ranges from 0
to RAND_MAX
.
rand
before a seed has been
established with srand
, it uses the value 1
as a default
seed.
To produce a different pseudo-random series each time your program is
run, do srand (time (0))
.
POSIX.1 extended the C standard functions to support reproducible random numbers in multi-threaded programs. However, the extension is badly designed and unsuitable for serious work.
RAND_MAX
just as rand
does. However, all its state is stored in the
seed argument. This means the RNG's state can only have as many
bits as the type unsigned int
has. This is far too few to
provide a good RNG.
If your program requires a reentrant RNG, we recommend you use the reentrant GNU extensions to the SVID random number generator. The POSIX.1 interface should only be used when the GNU extensions are not available.
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'.
0
to RAND_MAX
.
Note: Historically this function returned a long
int
value. On 64bit systems long int
would have been larger
than programs expected, so random
is now defined to return
exactly 32 bits.
srandom
function sets the state of the random number
generator 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 a different set of pseudo-random numbers each time your
program runs, do srandom (time (0))
.
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. It is initialized based on
seed. The size must be between 8 and 256 bytes, and should be a
power of two. 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.
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.
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 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.
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
.
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.
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.
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.
mrand48
function is similar to lrand48
. The only
difference is that the numbers returned are in the range -2^31
to
2^31
(exclusive).
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.
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).
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Not all hardware implements the entire IEEE 754 standard, or if it does, there may be a substantial performance penalty for using some of its features. For example, enabling traps on some processors forces the FPU to run unpipelined, which more than doubles calculation time.
Go to the first, previous, next, last section, table of contents.