C mathematical functions

Last updated

C mathematical operations are a group of functions in the standard library of the C programming language implementing basic mathematical functions. [1] [2] All functions use floating-point numbers in one manner or another. 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).

Contents

Overview of functions

Most of the mathematical functions 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. [1]

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. [3]

FunctionDescription
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 [4]
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. [3] 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
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)

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
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". [5] Implementations are provided by open-source projects that are not part of the standard library.

FunctionDescription
Error functions cerf computes the complex error function (C99)
cerfc computes 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. [6]

FunctionDescription
rand generates a pseudo-random number between 0 and RAND_MAX, inclusive.
srand initializes 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:

Implementations not necessarily under a name of libm include:

See also

Related Research Articles

ANSI C, ISO C, and Standard C are successive standards for the C programming language published by the American National Standards Institute (ANSI) and ISO/IEC JTC 1/SC 22/WG 14 of the International Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC). Historically, the names referred specifically to the original and best-supported version of the standard. Software developers writing in C are encouraged to conform to the standards, as doing so helps portability between compilers.

C is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of the targeted CPUs. It has found lasting use in operating systems, device drivers, protocol stacks, but its use in application software has been decreasing. C is commonly used on computer architectures that range from the largest supercomputers to the smallest microcontrollers and embedded systems.

In computing, NaN, standing for Not a Number, is a particular value of a numeric data type which is undefined or unrepresentable, such as the result of zero divided by zero. Systematic use of NaNs was introduced by the IEEE 754 floating-point standard in 1985, along with the representation of other non-finite quantities such as infinities.

In computer science, subnormal numbers are the subset of denormalized numbers that fill the underflow gap around zero in floating-point arithmetic. Any non-zero number with magnitude smaller than the smallest normal number is subnormal.

The C preprocessor is the macro preprocessor for several computer programming languages, such as C, Objective-C, C++, and a variety of Fortran languages. The preprocessor provides inclusion of header files, macro expansions, conditional compilation, and line control.

The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. Starting from the original ANSI C standard, it was developed at the same time as the C library POSIX specification, which is a superset of it. Since ANSI C was adopted by the International Organization for Standardization, the C standard library is also called the ISO C library.

In computer science, primitive data types are a set of basic data types from which all other data types are constructed. Specifically it often refers to the limited set of data representations in use by a particular processor, which all compiled programs must use. Most processors support a similar set of primitive data types, although the specific representations vary. More generally, "primitive data types" may refer to the standard data types built into a programming language. Data types which are not primitive are referred to as derived or composite.

C dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely malloc, realloc, calloc, aligned_alloc and free.

errno.h is a header file in the standard library of the C programming language. It defines macros for reporting and retrieving error conditions using the symbol errno.

<span class="mw-page-title-main">C syntax</span> Set of rules defining correctly structured programs

The syntax of the C programming language is the set of rules governing writing of software in the C language. It is designed to allow for programs that are extremely terse, have a close relationship with the resulting object code, and yet provide relatively high-level data abstraction. C was the first widely successful high-level language for portable operating-system development.

<span class="mw-page-title-main">C99</span> C programming language standard, 1999 revision

C99 is an informal name for ISO/IEC 9899:1999, a past version of the C programming language standard. It extends the previous version (C90) with new features for the language and the standard library, and helps implementations make better use of available computer hardware, such as IEEE 754-1985 floating-point arithmetic, and compiler technology. The C11 version of the C programming language standard, published in 2011, replaces C99.

In computer science and numerical analysis, unit in the last place or unit of least precision (ulp) is the spacing between two consecutive floating-point numbers, i.e., the value the least significant digit represents if it is 1. It is used as a measure of accuracy in numeric calculations.

<span class="mw-page-title-main">C data types</span> Data types supported by the C programming language

In the C programming language, data types constitute the semantics and characteristics of storage of data elements. They are expressed in the language syntax in form of declarations for memory locations or variables. Data types also determine the types of operations or methods of processing of data elements.

C++ Technical Report 1 (TR1) is the common name for ISO/IEC TR 19768, C++ Library Extensions, which is a document that proposed additions to the C++ standard library for the C++03 language standard. The additions include regular expressions, smart pointers, hash tables, and random number generators. TR1 was not a standard itself, but rather a draft document. However, most of its proposals became part of the later official standard, C++11. Before C++11 was standardized, vendors used this document as a guide to create extensions. The report's goal was "to build more widespread existing practice for an expanded C++ standard library".

The C and C++ programming languages are closely related but have many significant differences. C++ began as a fork of an early, pre-standardized C, and was designed to be mostly source-and-link compatible with C compilers of the time. Due to this, development tools for the two languages are often integrated into a single product, with the programmer able to specify C or C++ as their source language.

Some programming languages provide a complex data type for complex number storage and arithmetic as a built-in (primitive) data type.

C11 is an informal name for ISO/IEC 9899:2011, a past standard for the C programming language. It replaced C99 and has been superseded by C17. C11 mainly standardizes features already supported by common contemporary compilers, and includes a detailed memory model to better support multiple threads of execution. Due to delayed availability of conforming C99 implementations, C11 makes certain features optional, to make it easier to comply with the core language standard.

Zero to the power of zero, denoted by 00, is a mathematical expression that is either defined as 1 or left undefined, depending on context. In algebra and combinatorics, one typically defines 00 = 1. In mathematical analysis, the expression is sometimes left undefined. Computer programming languages and software also have differing ways of handling this expression.

The C programming language has a set of functions implementing operations on strings in its standard library. Various operations, such as copying, concatenation, tokenization and searching are supported. For character strings, the standard library uses the convention that strings are null-terminated: a string of n characters is represented as an array of n + 1 elements, the last of which is a "NUL character" with numeric value 0.

In computer science, a math library is a component of a programming language's standard library containing functions for the most common mathematical functions, such as trigonometry and exponentiation. Bit-twiddling and control functionalities related to floating point numbers may also be included.

References

  1. 1 2 ISO/IEC 9899:1999 specification (PDF). p. 212, § 7.12.
  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.
  3. 1 2 Prata, Stephen (2004). C primer plus. Sams Publishing. Appendix B, Section VIII: C99 Numeric Computational Enhancements. ISBN   0-672-32696-5.
  4. 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).
  5. man cerf(3), man cerfc(3), see e.g. https://linux.die.net/man/3/cerf.
  6. "The GNU C Library – ISO Random" . Retrieved 18 July 2018.
  7. Cordes, Peter. "intel - Where is Clang's '_mm256_pow_ps' intrinsic?". Stack Overflow.