How to calculate Euler constant or Euler powered in C++?

C++20 std::numbers::e

C++20 has also added an e constant to the standard library: http://eel.is/c++draft/numbers

I expect the usage to be like:

#include <math>
#include <iostream>

int main() {
    std::cout << std::numbers::e << std::endl;
}

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

The accepted proposal describes:

5.0. “Headers” [headers] In the table [tab:cpp.library.headers], a new header needs to be added.

[...]

namespace std {
namespace math { 
template<typename T > inline constexpr T e_v = unspecified;
inline constexpr double e = e_v<double>;

There is also a std::numbers::pi of course :-) How to use the PI constant in C++

These constants use the C++14 variable template feature: C++14 Variable Templates: what is their purpose? Any usage example?

In earlier versions of the draft, the constant was under std::math::e: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0631r7.pdf


If you can avoid using a preprocessor symbol you should. It will cause you trouble when you least expect it. E is likely going to be a variable.

Proposed solution:

#include <cmath>
const double EulerConstant = std::exp(1.0);

The advantage of calculating the constant instead of assigning a floating point literal is that it will produce a result with precision that matches the precision of the double data type for your particular C++ implementation. And it removes the possibility of introducing an error by accidentally skipping a digit.

As illustrated above, <cmath> does declare std::exp, so there is no need for you to roll your own.