C math.h Library Reference
Complete reference for math.h - power, roots, trigonometry, logarithms, and rounding functions.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Use power and root functions
- ✓Apply trigonometric functions
- ✓Work with logarithms
- ✓Round numbers correctly
?Why Use math.h?
C only provides basic arithmetic (+, -, *, /). For anything more complex, you need math.h!
Trig
sin, cos, tan
Power
pow, sqrt, exp
Log
log, log10
Round
ceil, floor
01Introduction to math.h
What is math.h?
<math.h> provides mathematical functions for trigonometry, logarithms, powers, rounding, and more.
Link Math Library
On Linux/GCC, you must link with -lm:gcc program.c -o program -lm
| Category | Functions |
|---|---|
| Power/Root | pow, sqrt, cbrt, hypot |
| Trigonometry | sin, cos, tan, asin, acos, atan |
| Logarithm | log, log10, log2, exp |
| Rounding | ceil, floor, round, trunc |
| Other | fabs, fmod, fmax, fmin |
02Power and Root Functions
| Function | Prototype | Description |
|---|---|---|
| pow() | double pow(double base, double exp) | base raised to exp (x^y) |
| sqrt() | double sqrt(double x) | Square root (√x) |
| cbrt() | double cbrt(double x) | Cube root (∛x) |
| hypot() | double hypot(double x, double y) | Hypotenuse √(x²+y²) |
1#include <stdio.h>2#include <math.h>34int main() {5 // Power6 printf("2^10 = %.0f\n", pow(2, 10)); // 10247 printf("5^3 = %.0f\n", pow(5, 3)); // 1258 9 // Square root10 printf("√16 = %.0f\n", sqrt(16)); // 411 printf("√2 = %.4f\n", sqrt(2)); // 1.414212 13 // Cube root14 printf("∛27 = %.0f\n", cbrt(27)); // 315 16 // Hypotenuse (Pythagorean theorem)17 printf("hypot(3,4) = %.0f\n", hypot(3, 4)); // 518 19 return 0;20}03Trigonometric Functions
Radians, Not Degrees!
All trig functions use radians. Convert: radians = degrees × (π / 180)
| Function | Prototype | Description |
|---|---|---|
| sin() | double sin(double x) | Sine (x in radians) |
| cos() | double cos(double x) | Cosine |
| tan() | double tan(double x) | Tangent |
| asin() | double asin(double x) | Arc sine (inverse) |
| acos() | double acos(double x) | Arc cosine |
| atan() | double atan(double x) | Arc tangent |
| atan2() | double atan2(double y, double x) | Arc tangent of y/x |
1#include <stdio.h>2#include <math.h>34#define PI 3.1415926535897932384656int main() {7 // Convert degrees to radians8 double deg = 45.0;9 double rad = deg * (PI / 180.0);10 11 printf("sin(45°) = %.4f\n", sin(rad)); // 0.707112 printf("cos(45°) = %.4f\n", cos(rad)); // 0.707113 printf("tan(45°) = %.4f\n", tan(rad)); // 1.000014 15 // Inverse trig (returns radians)16 double angle = asin(0.5); // 30° in radians17 printf("asin(0.5) = %.4f rad = %.1f°\n", 18 angle, angle * (180.0 / PI));19 20 // Use M_PI constant (if available)21 printf("sin(π/2) = %.4f\n", sin(M_PI / 2)); // 1.000022 23 return 0;24}04Exponential and Logarithmic
| Function | Prototype | Description |
|---|---|---|
| exp() | double exp(double x) | e^x (e = 2.718...) |
| log() | double log(double x) | Natural log (ln x) |
| log10() | double log10(double x) | Base-10 log |
| log2() | double log2(double x) | Base-2 log |
1#include <stdio.h>2#include <math.h>34int main() {5 // Exponential6 printf("e^1 = %.4f\n", exp(1)); // 2.71837 printf("e^2 = %.4f\n", exp(2)); // 7.38918 9 // Natural logarithm (base e)10 printf("ln(e) = %.4f\n", log(M_E)); // 1.000011 printf("ln(10) = %.4f\n", log(10)); // 2.302612 13 // Base-10 logarithm14 printf("log10(100) = %.4f\n", log10(100)); // 2.000015 printf("log10(1000) = %.4f\n", log10(1000)); // 3.000016 17 // Base-2 logarithm18 printf("log2(8) = %.4f\n", log2(8)); // 3.000019 printf("log2(1024) = %.4f\n", log2(1024)); // 10.000020 21 return 0;22}05Rounding Functions
| Function | Prototype | Description |
|---|---|---|
| ceil() | double ceil(double x) | Round up ⌈x⌉ |
| floor() | double floor(double x) | Round down ⌊x⌋ |
| round() | double round(double x) | Round to nearest |
| trunc() | double trunc(double x) | Truncate (toward 0) |
1#include <stdio.h>2#include <math.h>34int main() {5 double x = 3.7, y = -3.7;6 7 printf("Value ceil floor round trunc\n");8 printf("%.1f %.0f %.0f %.0f %.0f\n", 9 x, ceil(x), floor(x), round(x), trunc(x));10 printf("%.1f %.0f %.0f %.0f %.0f\n", 11 y, ceil(y), floor(y), round(y), trunc(y));12 13 // Output:14 // Value ceil floor round trunc15 // 3.7 4 3 4 316 // -3.7 -3 -4 -4 -317 18 return 0;19}Value ceil floor round trunc
3.7 4 3 4 3
-3.7 -3 -4 -4 -3
06Other Useful Functions
| Function | Prototype | Description |
|---|---|---|
| fabs() | double fabs(double x) | Absolute value |x| |
| fmod() | double fmod(double x, double y) | Floating-point modulo |
| fmax() | double fmax(double x, double y) | Maximum of x, y |
| fmin() | double fmin(double x, double y) | Minimum of x, y |
1#include <stdio.h>2#include <math.h>34int main() {5 // Absolute value6 printf("fabs(-5.5) = %.1f\n", fabs(-5.5)); // 5.57 8 // Floating-point modulo9 printf("fmod(5.3, 2) = %.1f\n", fmod(5.3, 2)); // 1.310 11 // Max and Min12 printf("fmax(3.5, 2.1) = %.1f\n", fmax(3.5, 2.1)); // 3.513 printf("fmin(3.5, 2.1) = %.1f\n", fmin(3.5, 2.1)); // 2.114 15 return 0;16}07Math Constants
| Constant | Value | Description |
|---|---|---|
| M_PI | 3.14159... | π (pi) |
| M_E | 2.71828... | e (Euler's number) |
| M_SQRT2 | 1.41421... | √2 |
| M_LN2 | 0.69314... | ln(2) |
Note
These constants may require #define _USE_MATH_DEFINESbefore including math.h on some compilers (MSVC).
!Code Pitfalls: Common Mistakes & What to Watch For
Copied code often provides math.h code that compiles but fails to link because it doesn't mention the -lm flag.
If you search online to "calculate the square root of a number," it will correctly include <math.h> and use sqrt(). But when you compile with gcc program.c, you get "undefined reference to sqrt." The Code rarely mentions you need gcc program.c -lm.
The Trap: Online sources focus on source code, not build systems. They might also use M_PI without mentioning that it requires #define _USE_MATH_DEFINES on MSVC, or compare floating-point results directly instead of using epsilon-based comparisons.
The Reality: On Unix-like systems, always link with -lm when using math.h. Never compare floats with ==; use fabs(a - b) < epsilon. Check for NaN and infinity using isnan() and isinf().
08bCommon Math Library Mistakes
Forgetting to Link -lm
Unlike other standard library functions, math.h functions require explicitly linking the math library. Always add -lm at the END of your gcc command: gcc program.c -o program -lm
Using Degrees Instead of Radians
All trigonometric functions use radians, not degrees. To convert:radians = degrees * M_PI / 180.0. A 90-degree angle is M_PI / 2 radians.
Integer Division in Math Functions
Passing integers where doubles are expected can cause issues.pow(2, 3) works, butsqrt(1/2) gives 0 because 1/2 is integer division! Use sqrt(1.0/2.0) instead.
09Frequently Asked Questions
Q:Why do I get "undefined reference to sqrt"?
A: You need to link the math library! Add -lm when compiling:gcc program.c -lm -o program. The -lm flag links the math library.
Q:How do I check if a number is NaN or infinity?
A: Use isnan(x)and isinf(x) macros from math.h. These return non-zero if x is NaN or infinity respectively. Never compare NaN with ==; use isnan() since NaN != NaN by definition.
Q:What's the difference between fmod() and %?
A: The % operator works only with integers.fmod(x, y) computes the floating-point remainder of x/y. For example, fmod(5.5, 2.0) returns 1.5, which you can't do with %.
Q:What's the difference between abs() and fabs()?
A: abs() (from stdlib.h) works on integers, fabs() (from math.h) works on floating-point numbers. Using abs() on a float truncates to integer first — always use fabs() for doubles!
Q:Do sin() and cos() use degrees or radians?
A: Radians! To convert degrees to radians: radians = degrees * M_PI / 180. For example, sin(90°) is sin(90 * M_PI / 180), which equals 1.0.
Q:M_PI is undefined — how do I fix it?
A: M_PI is a POSIX extension, not standard C. Add #define _USE_MATH_DEFINESBEFORE including math.h on MSVC, or define it yourself:#define M_PI 3.14159265358979323846
09Summary
Key Functions
Power/Root:
pow, sqrt, cbrt, hypot
Trig:
sin, cos, tan, asin, acos, atan
Log/Exp:
log, log10, log2, exp
Rounding:
ceil, floor, round, trunc
10Practical Tips for Math in C
Comparing Floating Point Numbers
Never use == to compare floats due to precision errors. Instead, check if the difference is within an acceptable epsilon:
if (fabs(a - b) < EPSILON) { /* equal */ }
Checking for Special Values
Use isnan(x) to check for Not-a-Number and isinf(x) for infinity. These arise from operations like 0.0/0.0 (NaN) or 1.0/0.0 (infinity). Always validate inputs before mathematical operations to avoid unexpected results.
Performance Considerations
Math functions can be computationally expensive. For performance-critical code, consider: using lookup tables for trig functions, approximations like fast inverse square root, or SIMD instructions for bulk operations. Profile before optimizing—modern CPUs have fast hardware math units.
Type-Generic Math (C11)
C11 introduced <tgmath.h> which provides type-generic macros. Instead of choosing between sinf(), sin(), and sinl(), you can just use sin()and it automatically selects the right version based on the argument type.
Handle Domain Errors
Functions like sqrt(-1) or log(0)produce domain errors. Check inputs before calling, or check for NaN/infinity in results usingisnan() and isinf().
Know Your Precision Limits
Floating-point has limited precision. After many operations, errors accumulate. Usedouble instead of float for better precision, and be aware that some exact decimal values cannot be represented exactly in binary floating-point.
Test Your Knowledge
Related Tutorials
C string.h Library Reference
Complete reference for string.h - strlen, strcpy, strcat, strcmp, searching, and memory functions.
C ctype.h Library Reference
Complete reference for ctype.h - character classification (isalpha, isdigit) and conversion (toupper, tolower).
C stdio.h Library Reference
Complete reference for stdio.h - all printf, scanf, and file functions with prototypes, parameters, and examples.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!