Loading lessons...
<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
| Function | Signature (as you'll call it) | Returns |
|---|---|---|
abs | abs(x) | the absolute value of x (no sign) |
ceil | ceil(x) | rounds x up to the next whole number |
floor | floor(x) | rounds x down to the previous whole number |
round | round(x) | rounds x to the nearest whole number (C++11) |
sqrt | sqrt(x) | the square root of x |
pow | pow(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
| Function | Signature | Returns |
|---|---|---|
exp | exp(x) | e raised to the power of x (inverse of natural log) |
log | log(x) | natural logarithm (base e) of x |
log10 | log10(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)
| Function | Signature | Returns |
|---|---|---|
sin | sin(x) | the sine of x |
cos | cos(x) | the cosine of x |
tan | tan(x) | the tangent of x |
asin | asin(x) | arc-sine (inverse sine), result in radians |
acos | acos(x) | arc-cosine, result in radians |
atan | atan(x) | arc-tangent, result in radians |
atan2 | atan2(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>)
| Function | Signature | Returns |
|---|---|---|
std::max | max(a, b) | larger of the two |
std::min | min(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 specialNaN(not a number) orinffor inputs without answers. - Watch the domain:
log(0)is negative infinity;sqrton a negative is not defined. - Overflows for huge numbers (
exp(1000)) produceinf. absin <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. logis natural log,log10is base 10.sin/cos/tanall want radians, not degrees.max/minare in <algorithm>, include it separately.