Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 135 ยท Standard Library

The Math Library

Use C's math.h library - pow, sqrt, fabs, floor, ceil, round, fmod, hypot and trigonometry - link it with -lm, and detect NaN, infinity and domain errors safely.

C's built-in operators only do arithmetic: +, -, *, / and %. Everything else, from square roots to sines to rounding, comes from the math library, declared in <math.h>. It's one of the most heavily optimized pieces of code on any system: these functions are accurate to within a rounding error or two and are often turned into single CPU instructions.

This lesson tours the functions you'll use most, grouped by job: powers and roots, absolute values, rounding, remainders, trigonometry, and exponentials and logarithms. It also covers the parts beginners trip over: linking with -lm, the difference between abs and fabs, and what happens when a calculation produces NaN or infinity. You'll want Floating-Point Numbers fresh in mind.

Using math.h and linking with -lm

Include the header and call the functions. They take and return double:

C A first look at math.h

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

On Linux and other Unix-like systems, the math functions live in a separate library, libm, so you must add -lm at the end of the link command. Our editor already does that:

Terminal
gcc -std=c23 -Wall -Wextra main.c -o main -lm

Forgetting it gives a linker error such as undefined reference to 'sqrt'. Confusingly, small test programs sometimes link without -lm, because GCC computes calls with constant arguments like sqrt(2.0) at compile time and never calls the library. As soon as the argument comes from a variable at run time, the error appears. On macOS and with MSVC on Windows, the math functions are part of the main C library and no flag is needed.

Note: Every function comes in three versions: sqrt for double, sqrtf for float and sqrtl for long double. Use the f versions in code that works with float (graphics, games, embedded) to avoid silent conversions to double. <tgmath.h> provides type-generic macros that pick the right version for you.

Powers, roots and distances

Function Computes Notes
pow(x, y) xy domain error for negative x with non-integer y
sqrt(x) โˆšx domain error for x < 0
cbrt(x) โˆ›x works for negative x: cbrt(-8) is -2
hypot(x, y) โˆš(xยฒ + yยฒ) no overflow in the intermediate squares
exp(x), exp2(x) ex, 2x
log(x), log10(x), log2(x) natural, base-10, base-2 logarithm log(0) is -infinity

pow returns a double, so don't use it for integer powers in tight loops or where exact results matter: for large values a double can't hold every integer (above 253 it skips some), and converting the result back to int truncates. For squaring, x * x is clearer and faster. For integer powers, a short loop is exact:

C pow versus exact integer powers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

339 is 4052555153018976267, which needs 62 bits. pow gets the nearest double, 4052555153018976256, while ipow (exponentiation by squaring) is exact. The distance example shows why hypot exists: squaring 1e200 overflows to infinity, but hypot scales internally and returns the right answer, about 1.41421e+200.

Absolute values: abs is not fabs

There are two families, in two headers:

  • abs(int), labs(long), llabs(long long) are integer functions in <stdlib.h>.
  • fabs(double), fabsf, fabsl are floating-point functions in <math.h>.

Calling abs(-2.7) converts the argument to int first and returns 2, a silent bug that GCC's -Wextra catches with the warning using integer absolute value function 'abs' when argument is of floating-point type 'double'. And abs(INT_MIN) is undefined behavior, because +2147483648 doesn't fit in an int.

Rounding

Converting a double to an integer type with a cast just chops off the fraction (rounds toward zero). The math library offers every other kind of rounding:

Function Rule 2.5 -2.5 2.7 -2.7
floor down, toward -โˆž 2 -3 2 -3
ceil up, toward +โˆž 3 -2 3 -2
trunc toward zero 2 -2 2 -2
round nearest, halves away from zero 3 -3 3 -3
rint / nearbyint nearest, halves to even (default mode) 2 -2 3 -3

They all return a double (so floor(2.7) is 2.0). lround and llround return a long/long long directly. Run the table yourself:

C Every rounding function side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Two surprises are worth noticing. First, rint rounds 2.5 to 2 and 3.5 to 4: "round half to even" (banker's rounding) avoids the upward bias of always rounding halves away from zero. Second, 2.675 can't be stored exactly in binary; the nearest double is 2.67499999999999982236431605997495353221893310546875, so %.2f correctly prints 2.67. Multiplying by 100 happens to round up to exactly 267.5, so round gives 2.68. If you need exact decimal amounts, like money, store integer cents instead.

Warning: Casting a double that is out of range for the target type, like (int)1e10 or (int)NAN, is undefined behavior. Check the range first, or use lround and check errno/fetestexcept for range errors.

Remainders: fmod and remainder

% only works on integers. For floating-point values, fmod(x, y) returns x - n*y where n is x/y rounded toward zero, so the result has the same sign as x, like % does for integers. remainder(x, y) rounds n to the nearest integer instead, giving a result between -y/2 and y/2, which is handy for wrapping angles.

C Wrapping angles with fmod and trig

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The trigonometric functions sin, cos, tan and their inverses asin, acos, atan all work in radians: multiply degrees by ฯ€/180 first. With 15 decimals sin(30ยฐ) looks like exactly 0.5, but printed with %.17g it's 0.49999999999999994: ฯ€ can't be stored exactly, so the input in radians is a tiny bit off, and the result is the correct sine of that input, not a bug. Prefer atan2(y, x) over atan(y / x): it knows the signs of both coordinates and returns the full range from -180ยฐ to 180ยฐ (as radians, -ฯ€ to ฯ€), and it handles x == 0 without dividing by zero. Above, the point (-1, 1) is at 135ยฐ, but atan(-1) can only say -45ยฐ.

M_PI is a POSIX extension that many headers provide, but strict standard modes (-std=c23 without extensions) may hide it. acos(-1.0) or a constexpr double pi = 3.14159265358979323846; (C23) works everywhere.

NaN, infinity and math errors

Floating-point math never traps by default. Instead, impossible or too-large results become special values:

  • Infinity (INFINITY, printed as inf) comes from overflow (exp(1000)), or dividing a nonzero number by zero.
  • NaN, "not a number" (NAN, printed as nan or -nan), comes from undefined operations like sqrt(-1), 0.0 / 0.0, log(-1) or inf - inf.

NaN is contagious: any arithmetic with a NaN gives NaN, and every comparison with NaN is false, even x == x. Test for it with the classification macros instead: isnan(x), isinf(x), isfinite(x) (neither) and fpclassify(x).

C Detecting NaN and infinity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

volatile is a trick for this demo: it stops GCC from computing the results at compile time (and from warning about the division by zero), so you see what happens at run time. The errno lines show the two kinds of math errors: a domain error (EDOM, "Numerical argument out of domain") when the input is outside the function's domain, and a range error (ERANGE, "Numerical result out of range") when the result is too big, or here a pole at log(0). Whether math functions set errno depends on math_errhandling; glibc does, but the more portable check is the result itself, with isnan and isinf. Error Handling covers errno in general.

More useful functions

A few more functions solve common problems precisely:

  • fmin(a, b), fmax(a, b): minimum and maximum that ignore a NaN argument.
  • fma(x, y, z): computes xยทy + z with a single rounding, more accurate than writing it out.
  • copysign(x, y): x with the sign of y; signbit(x) tests the sign, even of -0.0.
  • modf(x, &ip): splits x into integer and fractional parts.
  • frexp, ldexp: split a number into mantissa and power of two, and rebuild it.
  • expm1(x), log1p(x): accurate ex - 1 and log(1 + x) for tiny x, important in finance and statistics.

Comparing floating-point results for equality is rarely right, because of rounding. Use a tolerance, as explained in Floating-Point Numbers:

C
bool nearly_equal(double a, double b)
{
    return fabs(a - b) <= 1e-9 * fmax(1.0, fmax(fabs(a), fabs(b)));
}

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does abs(-2.7) return?

    abs is the int function from stdlib.h. The double -2.7 is converted to int (-2) and abs returns 2. Use fabs for floating-point values; GCC's -Wextra warns about this mistake.
  2. 2. Which call returns 2.0 for an argument of 2.5 in the default rounding mode?

    rint and nearbyint round halves to even, so 2.5 becomes 2. round and lround round halves away from zero (3), and ceil always rounds up (3).
  3. 3. What does fmod(-7.5, 2.0) return?

    fmod rounds the quotient toward zero (-3), so the result is -7.5 - (-3 * 2) = -1.5. The result has the sign of the first argument, like % on integers.
  4. 4. double x = sqrt(-1.0); Which test is true?

    sqrt of a negative number is NaN, and every comparison with NaN is false, even x == x and x == NAN. Use isnan to test for it.
  5. 5. A program using sqrt(x) on a variable compiles, but linking fails with undefined reference to 'sqrt' on Linux. What's the fix?

    On Linux the math functions are in libm, which you link with -lm. Calls with constant arguments sometimes work without it because GCC evaluates them at compile time.

Summary

  • <math.h> provides powers and roots (pow, sqrt, cbrt, hypot), exponentials and logs (exp, log, log10, log2), trigonometry in radians (sin, cos, tan, atan2, โ€ฆ) and more; f and l suffixes give the float and long double versions.
  • On Linux, link with -lm.
  • fabs is for floating-point values; abs/labs/llabs are integer functions from <stdlib.h>.
  • floor, ceil, trunc, round and rint cover every rounding rule; a cast truncates toward zero. Use integer cents for money.
  • fmod gives a remainder with the sign of x; remainder rounds to the nearest multiple.
  • Invalid operations produce NaN and overflow produces infinity; test with isnan, isinf and isfinite, never with ==.
  • Use exact integer loops for integer powers; pow returns a rounded double.

Next: Time and Date, where you'll read the clock, format dates with strftime and measure how long code takes.