简体   繁体   English

我将如何更清晰地编写此基本C ++程序,提高运行效率或返回更精确的数字?

[英]How would I code this basic C++ program more cleanly, to run more efficiently or to return a more precise figure?

It is supposed to evaluate e^pi - pi. 应该评估e ^ pi-pi。

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;
long double Pie();
long double Factorial(double n);
long double E();

int main()
{
    long double answer = pow(E(),Pie()) - Pie();
    cout << setprecision(20);
    cout << answer;

    return 0;
}
long double Pie()
{
    long double a = 1;
    long double b = (1 / sqrtl(2));
    long double t = (1.0 / 4.0);
    long double p = 1;

    long double aPlaceholder;
    for (int i = 1; i < 5; i++)
    {
        aPlaceholder = a;
        a = (a + b) / 2;
        b = sqrtl(aPlaceholder * b);
        t = t - p * (aPlaceholder - a) * (aPlaceholder - a);
        p = 2 * p;
    }
    long double nicePie;
    nicePie = (a + b) * (a + b) / (4 * t);
    return nicePie;
}

long double E()
{
    long double e = 0;
    for(double i = 0; i < 20; i++)
    e += 1.0 / Factorial(i);
    return e;
}

long double Factorial(double n)
{
    if(n == 0)
    return 1;
    int i = n - 1;
    while (i > 0)
    {
      n *= i;
      i--;
    }
    return n;
}

The scenario is that I want to evaluate e, raise it to the power of pi, and then subtract pi from the result and then print the answer to the screen. 场景是我要评估e,将其提高到pi的幂,然后从结果中减去pi,然后将答案打印到屏幕上。 Another aspect to the scenario is that this is a basic C++ program. 该方案的另一个方面是,这是一个基本的C ++程序。

cmath provides π and e as predefined constants as M_PI and M_E accurate within the precision of double , but it's not mandatory by C++ standard. cmathπe作为预定义常量提供为M_PIM_E ,它们的精度在double的精度范围内,但C ++标准并非强制要求。

You can just do double pi = acos(-1); 你可以做double pi = acos(-1);

  • <cmath> provides double long exp(double long) : http://www.cplusplus.com/reference/clibrary/cmath/exp/ as well as the Pi constant M_PI in double precision. <cmath>提供double long exp(double long)http : M_PI以及Pi常数M_PI ,具有双精度。
  • Boost provides Pi in long double precision : Boost提供的Pi具有long double精度:
    const long double pi = boost::math::constants::pi<long double>();

That being said there is some calculus in your code that you do multiple times while it is not needed: 话虽这么说,但您的代码中有一些演算,您可以多次执行,而无需这样做:

  • Pie is called twice. Pie叫两次。
  • In E() , Factorial is called at every iteration while you could multiply the previous result with i . E() ,每次迭代都会调用Factorial ,而您可以将先前的结果与i相乘。

.

long double E()
{
  long double e = 0;
  long double fact_i = 1;
  for(double i = 1; i < 20; i++)
  {
    fact_i *= i;
    e += 1.0 / fact_i;
  }
  return e;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM