问题
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?
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/18773343/how-to-calculate-euler-constant-or-euler-powered-in-c