Lesson 211 +5 XP

<cmath> Functions Reference

<cmath> Functions Reference

Math lives in the <cmath> header. These functions take numeric arguments and hand back a number you can use immediately.

About ranges and types

Almost all of these are double -> double: they take any double (or an int that upcasts) and return a double.

Basic math

FunctionSignature (as you'll call it)Returns
absabs(x)the absolute value of x (no sign)
ceilceil(x)rounds x up to the next whole number
floorfloor(x)rounds x down to the previous whole number
roundround(x)rounds x to the nearest whole number (C++11)
sqrtsqrt(x)the square root of x
powpow(x, y)x raised to the power y

Examples: ceil(2.1) is 3, floor(2.9) is 2, round(2.5) is 3, sqrt(16) is 4.

Powers and logarithms

FunctionSignatureReturns
expexp(x)e raised to the power of x (inverse of natural log)
loglog(x)natural logarithm (base e) of x
log10log10(x)base-10 logarithm of x

log gives base e; log10 gives base 10. Need a different base? Use log(x) / log(base).

Trigonometry (radians)

FunctionSignatureReturns
sinsin(x)the sine of x
coscos(x)the cosine of x
tantan(x)the tangent of x
asinasin(x)arc-sine (inverse sine), result in radians
acosacos(x)arc-cosine, result in radians
atanatan(x)arc-tangent, result in radians
atan2atan2(y, x)angle of the vector (y, x), handles the quadrant correctly

All angles in radians, not degrees. To convert: radians = degrees * 3.14159 / 180.

Min and max (from <algorithm>, not <cmath>)

FunctionSignatureReturns
std::maxmax(a, b)larger of the two
std::minmin(a, b)smaller of the two

Heads-up: max and min live in the <algorithm> header, not in <cmath>. Include both when you need math plus min/max.

Notes

  • Math can error out: sqrt(-1) has no real value. These functions often return a special NaN (not a number) or inf for inputs without answers.
  • Watch the domain: log(0) is negative infinity; sqrt on a negative is not defined.
  • Overflows for huge numbers (exp(1000)) produce inf.
  • abs in <cmath> handles doubles; the same-named one in <cstdlib> handles integers - the compiler picks the overload.

TL;DR

  • Fast common ones: sqrt, pow, abs, ceil, floor, round.
  • log is natural log, log10 is base 10.
  • sin/cos/tan all want radians, not degrees.
  • max/min are in <algorithm>, include it separately.