如何计算 C++ 中的欧拉常数或欧拉?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18773343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:11:54  来源:igfitidea点击:

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

c++eulers-number

提问by Tony

I am trying to find the more 'natural' way to use the number ein C/C++. I am focused on calculating the function e^n.

我试图找到在 C/C++ 中使用数字e的更“自然”的方式。我专注于计算函数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.

我认为“cmath”默认情况下不支持(函数和常量)。但是,可以启用它以包含编译器定义的常量,在本例中为M_E. 这可以通过包含语句来完成#define _USE_MATH_DEFINES

On the other hand, ecan be defined as a constant:

另一方面,e可以定义为常数:

#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?

说了这个。哪个是接近这个数学常数的最“标准”的方法?是其他图书馆吗?

回答by IInspectable

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

如果您可以避免使用预处理器符号,则应该这样做。它会在您最不期望的时候给您带来麻烦。E很可能会成为一个变量。

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 doubledata type for your particular C++ implementation. And it removes the possibility of introducing an error by accidentally skipping a digit.

计算常量而不是分配浮点文字的优点是它会产生一个精度与double特定 C++ 实现的数据类型精度相匹配的结果。它消除了因意外跳过数字而引入错误的可能性。

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

如上所示,<cmath>确实声明了std::exp,所以你不需要自己滚动。