From the course: C Standard Library

Mathematical functions - C Tutorial

From the course: C Standard Library

Start my 1-month free trial

Mathematical functions

Let me give you an overview of three header files that implement mathematical functions in the C standard library. First we have <math.h>, which implements common integer and floating point functions. For example, nearest integer functions, like floor, ceiling, round, and truncate. It also has power and exponential functions, including logarithms and roots. It has trigonometric functions and many more. Most of these functions are implemented for float, double, and long double types. This means that there are three versions for most functions. Next we have <complex.h>, which implements complex number representations as three types of different sizes. These are float, double, and long double. It has a variety of functions, including complex number implementations of most of the functions in <math.h>. There are also complex number specific functions, like carg, which returns the face angle of a complex number; cabs, which returns the norm of a complex number; creal and cimag return the real and imaginary part of a complex number respectively. And once more, most functions in <complex.h> are implemented in three versions, one for float complex, one for double complex, and one for long double complex. Now this variety of implementations of functions can get overwhelming because many functions have six different implementations. Three for real numbers and three for complex numbers. So in C99, a type-generic math header file called <tgmath.h> was developed. This was admittedly implementation-defined, so it's not really portable. The idea is to have a wrapper for <math.h> and <complex.h> where the programmer can freely use one single function to perform calculations on any of the six types. Just like built-in operators work in the language. So here are some examples. The sine function is implemented for both real and complex numbers, so the function named sin is used, and it's converted to double, float, or long in real or complex forms. Some functions don't exactly follow this standard. Like fabs, which could've been named abs. We also have real-only functions, like logarithms, and complex-only functions, like creal. Once more, generic types are not supported in C99, so implementation-defined workarounds were used. And so, there are several opinions about <tgmath.h>. Some programmers like it. Others, not so much.

Contents