C - Purpose of math.h
In C, math.h
is the Mathematics Header File.
It provides function prototypes and macros for performing mathematical calculations — like powers, roots, trigonometry, rounding, logarithms, and more.
1. Purpose of math.h
When you include:
#include <math.h>
you gain access to:
-
Standard mathematical functions (square root, sine, cosine, logarithms, etc.).
-
Common mathematical constants (like
INFINITY
,NAN
in C99). -
Macros for special floating-point values.
2. Important Notes
-
Most
math.h
functions work with double by default (variants exist forfloat
andlong double
in C99, likesqrtf()
andsqrtl()
). -
To compile a program using these functions on some compilers (like GCC), you may need to link the math library with
-lm
:gcc program.c -o program -lm
3. Commonly Used Functions
a) Basic Arithmetic
Function | Description |
---|---|
sqrt(x) |
Square root |
cbrt(x) (C99) |
Cube root |
pow(x, y) |
x raised to the power y |
fabs(x) |
Absolute value (floating-point) |
fmod(x, y) |
Floating-point remainder (x mod y) |
b) Trigonometric Functions
Function | Description |
---|---|
sin(x) |
Sine (x in radians) |
cos(x) |
Cosine |
tan(x) |
Tangent |
asin(x) |
Arc sine |
acos(x) |
Arc cosine |
atan(x) |
Arc tangent |
atan2(y, x) |
Arc tangent of y/x considering quadrants |
c) Exponential and Logarithmic
Function | Description |
---|---|
exp(x) |
e raised to the power x |
log(x) |
Natural logarithm (base e) |
log10(x) |
Base-10 logarithm |
log2(x) (C99) |
Base-2 logarithm |
d) Rounding and Remainder
Function | Description |
---|---|
ceil(x) |
Rounds up to nearest integer |
floor(x) |
Rounds down to nearest integer |
round(x) (C99) |
Rounds to nearest integer (ties to even) |
trunc(x) (C99) |
Truncates fractional part |
e) Hyperbolic Functions
Function | Description |
---|---|
sinh(x) |
Hyperbolic sine |
cosh(x) |
Hyperbolic cosine |
tanh(x) |
Hyperbolic tangent |
4. Example
#include <stdio.h>
#include <math.h>
int main() {
double num = 16.0;
printf("Square root of %.2f = %.2f\n", num, sqrt(num));
printf("2 raised to 3 = %.2f\n", pow(2, 3));
printf("Sine of 90 degrees = %.2f\n", sin(M_PI / 2)); // M_PI = 3.14159...
printf("Log base 10 of 1000 = %.2f\n", log10(1000));
return 0;
}