C and C++ mathematics facilities

C and C++ mathematics facilities are a group of functions in the standard libraries of the C and C++ programming language. The C standard library provides the header <math.h>. The C++ Standard Library provides <cmath>, which includes additional functionalities, as well as other headers such as <random> for random number generation.

General mathematics 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.

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.

In C++26, many of these functions were made constexpr.

Function Description
abs
labs
llabs
computes absolute value of an integer value
fabs computes absolute value of a floating-point value
div
ldiv
lldiv
computes the quotient and remainder of integer division
fmod remainder of the floating-point division operation
remainder signed remainder of the division operation
remquo signed remainder as well as the three last bits of the division operation
fma fused multiply-add operation
fmax larger of two floating-point values
fmin smaller of two floating-point values
fdim positive difference of two floating-point values
nan
nanf
nanl
returns a NaN (not-a-number)
Exponential
functions
exp returns e raised to the given power
exp2 returns 2 raised to the given power
expm1 returns e raised to the given power, minus one
log computes natural logarithm (to base e)
log2 computes binary logarithm (to base 2)
log10 computes common logarithm (to base 10)
log1p computes natural logarithm (to base e) of 1 plus the given number
ilogb extracts exponent of the number
logb extracts exponent of the number
Power
functions
sqrt computes square root
cbrt computes cubic root
hypot computes square root of the sum of the squares of two given numbers
pow raises a number to the given power
Trigonometric
functions
sin computes sine
cos computes cosine
tan computes tangent
asin computes arc sine
acos computes arc cosine
atan computes arc tangent
atan2 computes arc tangent, using signs to determine quadrants
Hyperbolic
functions
sinh computes hyperbolic sine
cosh computes hyperbolic cosine
tanh computes hyperbolic tangent
asinh computes hyperbolic arc sine
acosh computes hyperbolic arc cosine
atanh computes hyperbolic arc tangent
Error and
gamma
functions
erf computes error function
erfc computes complementary error function
lgamma computes natural logarithm of the absolute value of the gamma function
tgamma computes gamma function
Nearest
integer
floating-
point
operations
ceil returns the nearest integer not less than the given value
floor returns the nearest integer not greater than the given value
trunc returns the nearest integer not greater in magnitude than the given value
round
lround
llround
returns the nearest integer, rounding away from zero in halfway cases
nearbyint returns the nearest integer using current rounding mode
rint
lrint
llrint
returns the nearest integer using current rounding mode with exception if the result differs
Floating-
point
manipulation
functions
frexp decomposes a number into significand and a power of 2
ldexp multiplies a number by 2 raised to a power
modf decomposes a number into integer and fractional parts
scalbn
scalbln
multiplies a number by FLT_RADIX raised to a power
nextafter
nexttoward
returns next representable floating-point value towards the given value
copysign copies the sign of a floating-point value
Classification fpclassify categorizes the given floating-point value
isfinite checks if the argument has finite value
isinf checks if the argument is infinite
isnan checks if the argument is NaN
isnormal checks if the argument is normal
signbit checks 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. 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++).

Function Description
feclearexcept clears exceptions (C99)
fegetenv stores current floating-point environment (C99)
fegetexceptflag stores current status flags (C99)
fegetround retrieves current rounding direction (C99)
feholdexcept saves current floating-point environment and clears all exceptions (C99)
feraiseexcept raises a floating-point exception (C99)
fesetenv sets current floating-point environment (C99)
fesetexceptflag sets current status flags (C99)
fesetround sets current rounding direction (C99)
fetestexcept tests whether certain exceptions have been raised (C99)
feupdateenv restores floating-point environment, but keeps current exceptions (C99)

Checked integer arithmetic

C23 adds <stdckdint.h>, which provides checked integer arithmetic. In C23, these are macros; in C++ (since C++26), they are function templates. All functions take as a first parameter a pointer to the result, while the second and third parameters are the arguments themselves. The functions return false if the value assigned to *result correctly represents the mathematical result of the addition; otherwise true.

Function Description
ckd_add checked addition on two integers
ckd_sub checked subtraction on two integers
ckd_mul checked multiplication on two integers

Complex numbers

C complex utilities

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 C and C++ do not implement complex numbers in a code-compatible way – the latter instead provides the class std::complex<T> (for a floating point type T), which provides methods with constexpr support.

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.

Function Description
Basic
operations
cabs computes absolute value (C99)
carg computes argument of a complex number (C99)
cimag computes imaginary part of a complex number (C99)
creal computes real part of a complex number (C99)
conj computes complex conjugate (C99)
cproj computes complex projection into the Riemann sphere (C99)
Exponentiation
operations
cexp computes complex exponential (C99)
clog computes complex logarithm (C99)
csqrt computes complex square root (C99)
cpow computes complex power (C99)
Trigonometric
operations
csin computes complex sine (C99)
ccos computes complex cosine (C99)
ctan computes complex tangent (C99)
casin computes complex arc sine (C99)
cacos computes complex arc cosine (C99)
catan computes complex arc tangent (C99)
Hyperbolic
operations
csinh computes complex hyperbolic sine (C99)
ccosh computes complex hyperbolic cosine (C99)
ctanh computes complex hyperbolic tangent (C99)
casinh computes complex hyperbolic arc sine (C99)
cacosh computes complex hyperbolic arc cosine (C99)
catanh computes complex hyperbolic arc tangent (C99)

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

Function Description
Error functions cerf computes the complex error function (C99)
cerfc computes the complex complementary error function (C99)

C++ complex utilities

Types

C++ has its own type for a complex number, std::complex. Unlike C's built-in complex types, C++'s complex numbers have built-in methods.

Functions
Function Description
real returns the real part
imag returns the imaginary part
abs returns the magnitude of a complex number
arg returns the phase angle
norm returns the squared magnitude
conj returns the complex conjugate
proj returns the projection onto the Riemann sphere
polar constructs a complex number from magnitude and phase angle
exp complex base-e exponential
log complex natural logarithm with branch cuts along the negative real axis
log10 complex common logarithm with branch cuts along the negative real axis
pow complex power (one or both arguments may be complex)
sqrt complex square root in range of right half-plane
sin complex sine
cos complex cosine
tan complex tangent
asin complex arc sine
acos complex arc cosine
atan complex arc tangent
sinh complex hyperbolic sine
cosh complex hyperbolic cosine
tanh complex hyperbolic tangent
asinh complex arc hyperbolic sine
acosh complex arc hyperbolic cosine
atanh complex arc hyperbolic tangent

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.

Function Description
rand generates a pseudo-random number between 0 and RAND_MAX, inclusive. RAND_MAX
srand initializes a pseudo-random number generator
arc4random generates a pseudo-random number between 0 and UINT32_MAX, usually using a better algorithm than rand
arc4random_uniform generates a pseudo-random number between 0 and a maximum value.
arc4random_buf fill a buffer with a pseudo-random bitstream.
arc4random_stir initializes 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.

The C++ standard library provides another header, <random>, for its own random number generation facilities, in particular random number engines and probability distributions.

Special functions

Since C++17, C++ introduces special functions into the <cmath> header.

Function Description
assoc_laguerre computes associated Laguerre polynomials
assoc_legendre computes associated Legendre polynomials
beta computes beta function
comp_ellint_1 computes complete elliptic integral of the first kind
comp_ellint_2 computes complete elliptic integral of the second kind
comp_ellint_3 computes complete elliptic integral of the third kind
cyl_bessel_i computes regular modified cylindrical Bessel functions
cyl_bessel_j computes cylindrical Bessel functions of the first kind
cyl_bessel_k computes irregular modified cylindrical Bessel functions
cyl_neumann computes cylindrical Neumann functions
ellint_1 computes incomplete elliptic integral of the first kind
ellint_2 computes incomplete elliptic integral of the second kind
ellint_3 computes incomplete elliptic integral of the third kind
expint computes exponential integral
hermite computes Hermite polynomials
legendre computes Legendre polynomials
laguerre computes Laguerre polynomials
riemann_zeta computes Riemann zeta function
sph_bessel computes spherical Bessel functions of the first kind
sph_legendre computes spherical associated Legendre functions
sph_neumann computes spherical Neumann functions

Algorithms

These symbols are found in the <algorithm> header.

Minimum/maximum

Function Description
max, ranges::max returns the greater of the given values
max_element, ranges::max_element returns the largest element in a range
min, ranges::min returns the smaller of the given values
min_element, ranges::min_element returns the smallest element in a range
minmax, ranges::minmax returns the smaller and larger of two elements
minmax_element, ranges::minmax_element returns the smallest and largest elements in a range
clamp, ranges::clamp clamps a value between a pair of boundary values

Set operations

Function Description
includes, ranges::includes determines if one sequence is a subsequence of the other
set_difference, ranges::set_difference computes the difference between two sets
set_intersection, ranges::set_intersection computes the intersection of two sets
set_symmetric_difference, ranges::set_symmetric_difference computes the symmetric difference between two sets
set_union, ranges::set_union computes the union of two sets

Comparisons

Function Description
equal, ranges::equal determines if two sets of elements are the same
lexicographical_compare, ranges::lexicographical_compare compares two ranges lexicographically
lexicographical_compare_three_way compares two ranges using three-way comparison

Permutation operations

Function Description
is_permutation, ranges::is_permutation determines if a sequence is a permutation of another sequence
next_permutation, ranges::next_permutation generates the next greater lexicographic permutation of a range of elements
prev_permutation, ranges::prev_permutation generates the next smaller lexicographic permutation of a range of elements

Numeric algorithms

All symbols in this subsection are found in the <numeric> header.

Function Description
iota, ranges::iota fills a range with successive increments of the starting value
accumulate sums up or folds a range of elements
reduce folds a range out of order
transform_reduce applies an invocable (a transform) and then reduces out of order
inner_product computes the inner product of two ranges of elements
adjacent_difference computes the difference between adjacent elements in a range
partial_sum computes the partial sum of a range of elements
inclusive_sum computes the partial sum but includes the i-th input element in the i-th sum
exclusive_sum computes the partial sum but excludes the i-th input element in the i-th sum
transform_inclusive_scan applies an invocable, then calculates inclusive scan
transform_exclusive_scan applies an invocable, then calculates exclusive scan
Factor operations

C++17 introduces these factoring operations:

Function Description
gcd computes greatest common divisor
lcm computes lowest common multiple
Interpolation operations

C++20 introduces these interpolation operations:

Function Description
midpoint computes midpoint of two numbers/pointers
lerp computes linear interpolation
Saturation arithmetic

C++26 introduces these saturation arithmetic operations:

Function Description
saturating_add saturating addition on two integers
saturating_sub saturating subtraction on two integers
saturating_mul saturating multiplication on two integers
saturating_div saturating division on two integers
saturating_cast returns an integer value clamped to the range of another integer type
Carry-less product

C++29 introduces the following carry-less product operations:

Function Description
clmul carry-less product
widening_clmul widening carry-less product

Ratios

C++11 introduces the <ratio> header, which provides compile-time rational arithmetic (ratios) as a type. The std::ratio class represents an exact rational fraction. These are used in the std::chrono library, for example, to represent units of time.

Pre-defined ratios

The provided metric prefixes are the following:

Type Description
quecto 10−30
ronto 10−27
yocto 10−24
zepto 10−21
atto 10−18
femto 10−15
pico 10−12
nano 10−9 (see nano-)
micro 10−6 (see micro-)
milli 10−3 (see milli-)
centi 10−2 (see centi-)
deci 10−1 (see deci-)
deca 101 (see deca-)
hecto 102 (see hecto-)
kilo 103 (see kilo-)
mega 106 (see mega-)
giga 109 (see giga-)
tera 1012 (see tera-)
peta 1015
exa 1018
zetta 1021
yotta 1024
ronna 1027
quetta 1030

Functions

Function Description
ratio_add adds two ratios
ratio_subtract subtracts two ratios
ratio_multiply multiplies two ratios
ratio_divide divides two ratios
ratio_equal compares two ratios for equality
ratio_not_equal compares two ratios for inequality
ratio_less compares two ratios for less than
ratio_less_equal compares two ratios for less than or equal to
ratio_greater compares two ratios for greater than
ratio_greater_equal compares two ratios for greater than or equal to

Linear algebra

C++26 introduces linear algebra based on the Basic Linear Algebra Subprograms (BLAS) library in the <linalg> header, in namespace std::linalg. Note that here, the tensor type being referred to is std::mdspan.

Types

Class Description
scaled_accessor product of a scaling factor
conjugated_accessor complex conjugate
layout_transpose swaps the rightmost two indices, extents, and strides
layout_blas_packed mapping policy that represents a square that stores only the entries in one triangle

In-place transformations

Function Description
scaled returns the tensor scaled by the scaling factor
conjugate returns the complex conjugate of the tensor
transpose returns the transposed tensor
conjugate_transposed returns the conjugate transposed tensor

BLAS 1 functions

Function Description
setup_givens_rotation generates plane rotation
apply_givens_rotation applies plane rotation to vectors
swap_elements swaps all corresponding elements of tensor
scale overwrites tensor with the scaled tensor
copy copies from one tensor into another
add adds tensors together
dot returns non-conjugated dot product of two vectors
dotc returns conjugated dot product of two vectors
vector_sum_of_squares returns scaled sum of squares of vector elements
vector_two_norm returns Euclidean norm of a vector
vector_abs_sum returns sum of absolute values of vector elements
vector_idx_abs_max returns index of maximum absolute value of vector elements
matrix_frob_norm returns Frobenius norm (square root of sum of squares of all tensor elements)
matrix_one_norm returns Manhattan norm (sum of absolute values of all tensor elements)
matrix_inf_norm returns Chebyshev norm (maximum absolute value of all tensor elements)

BLAS 2 functions

Function Description
matrix_vector_product computes matrix-vector product
symmetric_matrix_vector_product computes symmetric matrix-vector product
hermitian_matrix_vector_product computes Hermitian matrix-vector product
triangular_matrix_vector_product computes triangular matrix-vector product
triangular_matrix_vector_solve solves a triangular linear system
matrix_rank_1_update performs nonsymmetric nonconjugated rank-1 update of a matrix
matrix_rank_1_update_c performs nonsymmetric conjugated rank-1 update of a matrix
symmetric_matrix_rank_1_update performs rank-1 update of a symmetric matrix
hermitian_matrix_rank_1_update performs rank-1 update of a Hermitian matrix
symmetric_matrix_rank_2_update performs rank-2 update of a symmetric matrix
hermitian_matrix_rank_2_update performs rank-2 update of a Hermitian matrix

BLAS 3 functions

Function Description
matrix_product computes matrix-matrix product
symmetric_matrix_product computes symmetric matrix-matrix product
hermitian_matrix_product computes Hermitian matrix-matrix product
triangular_matrix_product computes triangular matrix-matrix product
triangular_matrix_left_product computes triangular matrix-matrix product
triangular_matrix_right_product computes triangular matrix-matrix product
symmetric_matrix_rank_k_update performs rank-k update of a symmetric matrix
hermitian_matrix_rank_k_update performs rank-k update of a Hermitian matrix
symmetric_matrix_rank_2k_update performs rank-2k update of a symmetric matrix
hermitian_matrix_rank_2k_update performs rank-2k update of a Hermitian matrix
triangular_matrix_matrix_left_solve solves multiple triangular linear systems
triangular_matrix_matrix_right_solve solves multiple triangular linear systems

Bit manipulation

C++20 introduces bit manipulation in the <bit> header. endian is an enum with values endian::little, endian::big, and endian::native representing little-endian, big-endian and the native endianness of the platform; if the platform uses mixed-endian, it is neither equal to little or big.

Function Description
bit_cast reinterpret the object representation of one type as that of another (see type punning)
byteswap reverses the bytes in the given integer value
has_single_bit checks if a number is an integral power of 2
bit_ceil finds the smallest integral power of 2 not less than the given value
bit_floor finds the largest integral power of 2 not greater than the given value
bit_width finds the smallest number of bits needed to represent the given value
shl shifts to the left without possibility of undefined behaviour
shr shifts to the right without possibility of undefined behaviour
rotl computes the result of bitwise left-rotation
rotr computes the result of bitwise right-rotation
countl_zero counts the number of consecutive 0 bits, starting from most significant bit
countl_one counts the number of consecutive 1 bits, starting from most significant bit
countr_zero counts the number of consecutive 0 bits, starting from least significant bit
countr_one counts the number of consecutive 1 bits, starting from least significant bit
popcount counts the number of 1 in an unsigned integer
bit_reverse reverses the bits in an integer
bit_repeat repeats/broadcasts a bit pattern of specified length
bit_compress compresses bits of an operand using a mask PEXT
bit_expand expands bits from an operand using a mask PDEP

Constants

C does not define mathematical constants, however in some compiler extensions, macros like M_PI and M_E exist.

Since C++20, in C++ the following constants (of double type) are defined, in the header <numbers> and in namespace std::numbers:

Constant Description
e e (see e)
log2e log2(e)
log10e log10(e)
pi π (see pi)
inv_pi 1π
ln2 ln⁡(2) (see natural logarithm of 2)
ln10 ln⁡(10)
sqrt2 2 (see square root of 2)
sqrt3 3 (see square root of 3)
inv_sqrt3 13
egamma γ (see Euler's constant)
phi ϕ (see golden ratio)

Note that the above are predefined constants, but variable templates (with the same names followed by a '_v' suffix) can be used to truncate the constant to a specific precision, for example pi_v<float> truncates pi to float precision.

Random number generation

C++11 introduces random number generation to the standard library, in the header <random>.

Concepts

Concept Description
uniform_random_bit_generator specifies that a type qualifies as a uniform random bit generator

Random number engines

Class Description
linear_congruential_engine linear congruential generator
mersenne_twister_engine Mersenne Twister
subtract_with_carry_engine lagged Fibonacci generator
philox_engine counter-based parallelisable generator

Random number engine adaptors

Class Description
discard_block_engine discards some output of a random number engine
independent_bits_engine packs the output of a random number engine into blocks of a specified number of bits
shuffle_order_engine delivers the output of a random number engine in a different order

Utilities

Class Description
random_device non-deterministic random number generator using hardware entropy source
seed_seq general-purpose bias-eliminating scrambled seed sequence generator

Distributions

Uniform distributions

Class Description
uniform_int_distribution discrete uniform distribution
uniform_real_distribution continuous uniform distribution

Bernoulli distributions

Class Description
bernoulli_distribution Bernoulli distribution for bool values
binomial_distribution binomial distribution for integer values
negative_binomial_distribution negative binomial distribution for integer values
geometric_distribution geometric distribution for integer values

Poisson distributions

Class Description
poisson_distribution Poisson distribution for integer values
exponential_distribution exponential distribution for real values
gamma_distribution gamma distribution for real values
weibull_distribution Weibull distribution for real values
extreme_value_distribution extreme value distribution for real values

Normal distributions

Class Description
normal_distribution normal distribution for real values
lognormal_distribution log-normal distribution for real values
chi_squared_distribution chi-squared distribution for real values
cauchy_distribution Cauchy distribution for real values
fisher_f_distribution F-distribution for real values
student_t_distribution Student's t-distribution for real values

Sampling distributions

Class Description
discrete_distribution produces integer values on a discrete distribution
piecewise_constant_distribution produces real values distributed on constant subintervals
piecewise_linear_distribution produces real values distributed on defined subintervals

Functions

Function Description
generate_canonical evenly distributes real numbers of given precision across the range [0,1)
ranges::generate_random fills a range with random numbers from a uniform random bit generator

SIMD

C++26 introduces for single instruction, multiple data (SIMD) operations in the standard library, in the header <simd> and in namespace std::simd.

Types

Class Description
basic_vec data-parallel type
vec standard SIMD vector with pre-specified ABI width
basic_mask data-parallel type with bool elements
mask standard SIMD mask with pre-specified ABI width
flags load and store flags for data-parallel types
alignment obtains an appropriate alignment for flag_aligned
rebind changes element type of the data-parallel type
resize changes the width of the data-parallel type

Functions

Function Description
unchecked_load loads elements from a contiguous range to basic_vec without bounds checks
partial_load loads elements from a contiguous range to basic_vec, zero-padding out-of-bounds elements
unchecked_store stores elements from a basic_vec to a contiguous range without bounds checks
partial_store stores in-bounds elements from a basic_vec to a contiguous range
chunk splits single data-parallel object to multiple ones
cat concatenates multiple data-parallel objects into a single one
all_of checks if all elements in a basic_mask are true
any_of checks if at least one element in a basic_mask is true
none_of checks if no elements in a basic_mask are true
reduce_count reduction of basic_mask to number of true values
reduce_min_index reduction of basic_mask to the index of the first true value
reduce_max_index reduction of basic_mask to the index of the last true value
reduce reduces all values in basic_vec over a specified binary operation to a single value
reduce_min returns the smallest element in basic_vec
reduce_max returns the largest element in basic_vec
min returns the element-wise smaller of two basic_vec objects
max returns the element-wise larger of two basic_vec objects
minmax returns the element-wise smaller and larger of two basic_vec objects
clamp element-wise clamp operation for basic_vec
select element-wise selection using conditional operator

Constants

Constant Description
flag_default default flag used on load and store operations
flag_convert flag enabling conversions that are not value-preserving on load and store operations
flag_aligned flag indicating alignment of the load-store address to some specified storage to the value of alignment
flag_overaligned flag indicating alignment of the load-store address to some specified storage to the specified alignment

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:

Implementations not necessarily under a name of libm include:

See also