Menu
Home Explore People Places Arts History Plants & Animals Science Life & Culture Technology
On this page
C mathematical functions
C standard library header file providing mathematical functions

C mathematical operations are a group of functions in the standard library of the C programming language implementing basic mathematical functions. Different C standards provide different, albeit backwards-compatible, sets of functions. Most of these functions are also available in the C++ standard library, though in different headers (the C headers are included as well, but only as a deprecated compatibility feature).

We don't have any images related to C mathematical functions yet.
We don't have any YouTube videos related to C mathematical functions yet.
We don't have any PDF documents related to C mathematical functions yet.
We don't have any Books related to C mathematical functions yet.
We don't have any archived web articles related to C mathematical functions yet.

Overview of functions

Most of the mathematical functions, which use floating-point numbers, are defined in <math.h> (<cmath> header in C++). The functions that operate on integers, such as abs, labs, div, and ldiv, are instead defined in the <stdlib.h> header (<cstdlib> header in C++).

Any functions that operate on angles use radians as the unit of angle.3

Not all of these functions are available in the C89 version of the standard. For those that are, the functions accept only type double for the floating-point arguments, leading to expensive type conversions in code that otherwise used single-precision float values. In C99, this shortcoming was fixed by introducing new sets of functions that work on float and long double arguments. Those functions are identified by f and l suffixes respectively.4

FunctionDescription
abslabsllabscomputes absolute value of an integer value
fabscomputes absolute value of a floating-point value
divldivlldivcomputes the quotient and remainder of integer division
fmodremainder of the floating-point division operation
remaindersigned remainder of the division operation
remquosigned remainder as well as the three last bits of the division operation
fmafused multiply-add operation
fmaxlarger of two floating-point values
fminsmaller of two floating-point values
fdimpositive difference of two floating-point values
nannanfnanlreturns a NaN (not-a-number)
Exponentialfunctionsexpreturns e raised to the given power
exp2returns 2 raised to the given power
expm1returns e raised to the given power, minus one
logcomputes natural logarithm (to base e)
log2computes binary logarithm (to base 2)
log10computes common logarithm (to base 10)
log1pcomputes natural logarithm (to base e) of 1 plus the given number
ilogbextracts exponent of the number
logbextracts exponent of the number
Powerfunctionssqrtcomputes square root
cbrtcomputes cubic root
hypotcomputes square root of the sum of the squares of two given numbers
powraises a number to the given power5
Trigonometricfunctionssincomputes sine
coscomputes cosine
tancomputes tangent
asincomputes arc sine
acoscomputes arc cosine
atancomputes arc tangent
atan2computes arc tangent, using signs to determine quadrants
Hyperbolicfunctionssinhcomputes hyperbolic sine
coshcomputes hyperbolic cosine
tanhcomputes hyperbolic tangent
asinhcomputes hyperbolic arc sine
acoshcomputes hyperbolic arc cosine
atanhcomputes hyperbolic arc tangent
Error andgamma functionserfcomputes error function
erfccomputes complementary error function
lgammacomputes natural logarithm of the absolute value of the gamma function
tgammacomputes gamma function
Nearestintegerfloating-pointoperationsceilreturns the nearest integer not less than the given value
floorreturns the nearest integer not greater than the given value
truncreturns the nearest integer not greater in magnitude than the given value
roundlroundllroundreturns the nearest integer, rounding away from zero in halfway cases
nearbyintreturns the nearest integer using current rounding mode
rintlrintllrintreturns the nearest integer using current rounding mode with exception if the result differs
Floating-pointmanipulationfunctionsfrexpdecomposes a number into significand and a power of 2
ldexpmultiplies a number by 2 raised to a power
modfdecomposes a number into integer and fractional parts
scalbnscalblnmultiplies a number by FLT_RADIX raised to a power
nextafternexttowardreturns next representable floating-point value towards the given value
copysigncopies the sign of a floating-point value
Classificationfpclassifycategorizes the given floating-point value
isfinitechecks if the argument has finite value
isinfchecks if the argument is infinite
isnanchecks if the argument is NaN
isnormalchecks if the argument is normal
signbitchecks if the sign of the argument is negative

Floating-point environment

C99 adds several functions and types for fine-grained control of floating-point environment.6 These functions can be used to control a variety of settings that affect floating-point computations, for example, the rounding mode, on what conditions exceptions occur, when numbers are flushed to zero, etc. The floating-point environment functions and types are defined in <fenv.h> header (<cfenv> in C++).

FunctionDescription
feclearexceptclears exceptions (C99)
fegetenvstores current floating-point environment (C99)
fegetexceptflagstores current status flags (C99)
fegetroundretrieves current rounding direction (C99)
feholdexceptsaves current floating-point environment and clears all exceptions (C99)
feraiseexceptraises a floating-point exception (C99)
fesetenvsets current floating-point environment (C99)
fesetexceptflagsets current status flags (C99)
fesetroundsets current rounding direction (C99)
fetestexcepttests whether certain exceptions have been raised (C99)
feupdateenvrestores floating-point environment, but keeps current exceptions (C99)

Complex numbers

C99 adds a new _Complex keyword (and complex convenience macro; only available if the <complex.h> header is included) that provides support for complex numbers. Any floating-point type can be modified with complex, and is then defined as a pair of floating-point numbers. Note that C99 and C++ do not implement complex numbers in a code-compatible way – the latter instead provides the class std::complex.

All operations on complex numbers are defined in the <complex.h> header. As with the real-valued functions, an f or l suffix denotes the float complex or long double complex variant of the function.

FunctionDescription
Basicoperationscabscomputes absolute value (C99)
cargcomputes argument of a complex number (C99)
cimagcomputes imaginary part of a complex number (C99)
crealcomputes real part of a complex number (C99)
conjcomputes complex conjugate (C99)
cprojcomputes complex projection into the Riemann sphere (C99)
Exponentiationoperationscexpcomputes complex exponential (C99)
clogcomputes complex logarithm (C99)
csqrtcomputes complex square root (C99)
cpowcomputes complex power (C99)
Trigonometricoperationscsincomputes complex sine (C99)
ccoscomputes complex cosine (C99)
ctancomputes complex tangent (C99)
casincomputes complex arc sine (C99)
cacoscomputes complex arc cosine (C99)
catancomputes complex arc tangent (C99)
Hyperbolicoperationscsinhcomputes complex hyperbolic sine (C99)
ccoshcomputes complex hyperbolic cosine (C99)
ctanhcomputes complex hyperbolic tangent (C99)
casinhcomputes complex hyperbolic arc sine (C99)
cacoshcomputes complex hyperbolic arc cosine (C99)
catanhcomputes complex hyperbolic arc tangent (C99)

A few more complex functions are "reserved for future use in C99".7 Implementations are provided by open-source projects that are not part of the standard library.

FunctionDescription
Error functionscerfcomputes the complex error function (C99)
cerfccomputes the complex complementary error function (C99)

Type-generic functions

The header <tgmath.h> defines a type-generic macro for each mathematical function defined in <math.h> and <complex.h>. This adds a limited support for function overloading of the mathematical functions: the same function name can be used with different types of parameters; the actual function will be selected at compile time according to the types of the parameters.

Each type-generic macro that corresponds to a function that is defined for both real and complex numbers encapsulates a total of 6 different functions: float, double and long double, and their complex variants. The type-generic macros that correspond to a function that is defined for only real numbers encapsulates a total of 3 different functions: float, double and long double variants of the function.

The C++ language includes native support for function overloading and thus does not provide the <tgmath.h> header even as a compatibility feature.

Random-number generation

The header <stdlib.h> (<cstdlib> in C++) defines several functions that can be used for statistically random number generation.8

FunctionDescription
randgenerates a pseudo-random number between 0 and RAND_MAX, inclusive.
srandinitializes a pseudo-random number generator
arc4randomgenerates a pseudo-random number between 0 and UINT32_MAX, usually using a better algorithm than rand
arc4random_uniformgenerates a pseudo-random number between 0 and a maximum value.
arc4random_buffill a buffer with a pseudo-random bitstream.
arc4random_stirinitializes a pseudo-random number generator.

The arc4random family of random number functions are not defined in POSIX standard, but is found in some common libc implementations. It used to refer to the keystream generator of a leaked version of RC4 cipher (hence "alleged RC4"), but different algorithms, usually from other ciphers like ChaCha20, have been implemented since using the same name.

The quality of randomness from rand are usually too weak to be even considered statistically random, and it requires explicit seeding. It is usually advised to use arc4random instead of rand when possible. Some C libraries implement rand using arc4random_uniform internally.

Implementations

Under POSIX systems like Linux and BSD, the mathematical functions (as declared in <math.h>) are bundled separately in the mathematical library libm. Therefore, if any of those functions are used, the linker must be given the directive -lm. There are various libm implementations, including:

See also: Rounding § Table-maker's dilemma

Implementations not necessarily under a name of libm include:

See also

The Wikibook C Programming has a page on the topic of: C Programming/C Reference

References

  1. ISO/IEC 9899:1999 specification (PDF). p. 212, § 7.12. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf

  2. Prata, Stephen (2004). C primer plus. Sams Publishing. Appendix B, Section V: The Standard ANSI C Library with C99 Additions. ISBN 0-672-32696-5. 0-672-32696-5

  3. ISO/IEC 9899:1999 specification (PDF). p. 212, § 7.12. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf

  4. Prata, Stephen (2004). C primer plus. Sams Publishing. Appendix B, Section VIII: C99 Numeric Computational Enhancements. ISBN 0-672-32696-5. 0-672-32696-5

  5. Notationally, it may seem convenient to use pow(x,2) or pow(x,3) to compute squares or cubes. However, this is not advisable in time-critical code. Unless an implementation takes special care of these cases at compile time, x*x or x*x*x will execute much faster. Also, sqrt(x) and cbrt(x) should be preferred over pow(x,.5) or pow(x,1./3).

  6. Prata, Stephen (2004). C primer plus. Sams Publishing. Appendix B, Section VIII: C99 Numeric Computational Enhancements. ISBN 0-672-32696-5. 0-672-32696-5

  7. man cerf(3), man cerfc(3), see e.g. https://linux.die.net/man/3/cerf. https://linux.die.net/man/3/cerf

  8. "The GNU C Library – ISO Random". Retrieved 18 July 2018. https://www.gnu.org/software/libc/manual/html_node/ISO-Random.html

  9. "Math Functions — The LLVM C Library". libc.llvm.org. https://libc.llvm.org/math/index.html

  10. "RLibm: Rutgers Architecture and Programming Languages Lab's Correctly Rounded Libm". people.cs.rutgers.edu. https://people.cs.rutgers.edu/~sn349/rlibm/

  11. Cordes, Peter. "intel - Where is Clang's '_mm256_pow_ps' intrinsic?". Stack Overflow. https://stackoverflow.com/a/36637424