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

I am trying to find a 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, you can include constants defined by the compiler, in this case M_E . You can do this by including the #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 it. Which one is the โ€œstandardโ€ way to approach this mathematical constant? Is this some other library?

+11
c ++ eulers-number
source share
2 answers

If you can avoid using the preprocessor character, you should. This will cause you problems when you least expect it. E is likely to be a variable.

Proposed Solution:

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

The advantage of calculating a constant instead of assigning a floating point literal is that it will produce a result with an accuracy that matches the accuracy of the double data type for your specific C ++ implementation. And this eliminates the possibility of introducing errors by accidentally skipping a number.

As shown above, <cmath> declares std::exp , so you don't need to roll back your own.

+19
source share

C ++ 20 std::numbers::e

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

I expect usage to be like:

 #include <math> #include <iostream> int main() { std::cout << std::numbers::e << std::endl; } 

I will try when support comes to GCC, GCC 9.1.0 with g++-9 -std=c++2a still does not support it.

The accepted proposal describes:

5.0. Headers [headers] In the table [tab: cpp.library.headers], a new header must 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 std::numbers::pi , of course :-) How to use the PI constant in C ++

These constants use the C ++ 14 variable template function: C ++ 14 Variable templates: what is their purpose? Any use case?

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

+2
source share

All Articles