I am trying to find the more 'natural' way to use the number e in C/C++. I am focused on calculating the function e^n.
I think that 'cmath', by default, does not provide support for both (function and constant). However, it can be enabled to include constants defined by the compiler, in this case, M_E
. This can be done by including the statement #define _USE_MATH_DEFINES
.
On the other hand, e can be defined as a constant:
#define E 2.71828182845904523536;
or
const double EULER = 2.71828182845904523536;
Said this. Which one is the most 'standard' way to approach to this mathematical constant? Is it any other library?
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.