In C++, std::exp(x) calculates e to the power of x. The number e is about 2.71828. It appears in growth and decay: money with continuous interest, a cooling cup of tea, and a virus that spreads.
exp() and std::log() are opposites: log(exp(x)) gives back x. The function grows very fast, so a large x quickly becomes too big for a double and the result is inf.
std::exp() is declared in <cmath> and is part of the group Exponential and logarithm. Exponentials and logarithms undo each other. A logarithm of zero is -inf, and a logarithm of a negative number is NaN.
Syntax
Include <cmath> and call std::exp. Start with these lines.
C++
double a = std::exp(1.0); // double version
float b = std::exp(1.0f); // float version
Call
What it does
std::exp(1.0)
Passes a double and returns a double. Here the result is 2.71828.
std::exp(1.0f)
Passes a float, so the float overload runs and returns a float.
std::exp(0)
An integer is converted to double. Returns 1 as a double.
Write std::exp so the C++ overloads for float, double, and long double are used.
Library declarations
C++
float exp(float x);
double exp(double x);
long double exp(long double x);
double exp(Integer x); // for integer types
Parameters
Parameter
Description
x
Required. The exponent. It can be positive, negative, or zero. An integer is converted to double.
Return Value
Return Value
Description
ex
The exponential of x, always greater than zero.
inf
The result is too big for the type (about x > 709.78 for a double). This is an overflow.
0
The result is too small to store, such as exp(-800). This is an underflow.
C++ Examples
Example 1 — Common Values of exp()
Print e to a few powers, including zero and a negative power.
C++
#include <cmath>
#include <iostream>
int main() {
double values[] = {0.0, 1.0, 2.0, -1.0};
for (double v : values) {
std::cout << "exp(" << v << ") = " << std::exp(v) << '\n';
}
return 0;
}
exp(709) = 8.21841e+307
exp(710) is inf: 1
exp(-800) = 0
How It Works
exp(709) is the biggest power of e that fits in a double. It prints as 8.21841e+307.
One step further, exp(710) is too big and becomes inf. std::isinf() prints 1, and the program does not crash.
A very negative exponent gives a number too tiny to store, so exp(-800) becomes 0.
Frequently Asked Questions
std::exp(x) returns e raised to the power x. The number e is about 2.71828, so exp(1.0) is 2.71828 and exp(0.0) is 1.
e to the power x as float, double, or long double. A very large x gives inf, and a very negative x gives 0.
The number e is about 2.718281828. There is no named constant before C++20, but std::exp(1.0) gives it. In C++20 you can use std::numbers::e from <numbers>.
exp(x) is e to the power x. pow(a, b) is a to the power b, for any base. exp(x) is faster and more exact than pow(2.718281828, x).
Include <cmath> and write std::exp(). That always works and picks the C++ overloads. The global name ::exp often works too, but the standard does not promise it, and it may only take a double.