c++程序来计算e^x

C++ program to calculate e^x

本文关键字:计算 程序 c++      更新时间:2023-10-16

我知道这个问题有很多例子,但我试着自己写一个不同的例子。这是用泰勒级数e^x = 1 + x/1!+ x ^ 2/2 !+ x ^ 3/3 !+……我的代码编译和运行,但它不会输出一些估算的正确答案,我不知道为什么。这是可用的代码吗?还是我应该放弃它?

    #include <iostream>
    #include <cmath>
    using namespace std;
    int main()
   {
        double final,power,end_n = 1.0,e=1.0,x=2.0, n;
        cout<< "n: ";
       // usually enter 5 for test
        cin>> n;
        while (n>1){
            power = pow(x,n);
            end_n = end_n*n;
            e= (power/end_n)+e;
            n--;
        }
        final =e+x;
        cout<< final;
      return 0;
    }
我真的完全不知道你的理由是什么。该特定展开的代码非常简单:
double x;
cin >> x;
double oldres, res=1, top=1, bottom=1;
int iter=1;
do {
  oldres=res;                           // to calculate the difference between iterations
  ++iter;                               // next iteration
  top*=x;                               // multiply by one x for each iteration
  bottom*=(iter-1);                     // multiply by the iteration number for each iteration
  res+=top/bottom;                      // and add the fraction to the result
} while(fabs(res-oldres)>.1);           // while the difference is still large
cout << res;                            // done, show the result

要非常清楚一些其他人在暗示:如果你的循环计数从1到n,那么end_n将等于n!每一步。但是倒数,它没有。请看从1到5的例子:

向前

n | n!
1 | 1
2 | 2
3 | 6
4 | 24
5 | 120
向后

n | end_n
5 | 5
4 | 20
3 | 60
2 | 120
1 | 120

由于你的分母绝对没有一个是正确的,如果你的代码只对一些输入是错误的,这是令人惊讶的——事实上,它可能只对x=0是正确的。

最后,我希望这只是一个学习的练习。如果你真的需要e^x的值,你应该使用exp(x)

我想你很接近了。也许你想更像这样:

#include <iostream>
#include <cmath>
using namespace std;
double factorial(long n)
{
    double result = n;
    while(--n) result*=n;
}
int main()
{
    long n, power;
    double final, e=1.0, x=2.0;
    cout<< "n: ";
    // usually enter 5 for test
    cin>> n;
    while (n>1)
    {
        power = pow((double)x, (double)n);
        end_n = factorial(n);
        e = (power/end_n)+e;
        n--;
    }
    final = e+x;
    cout<< final;
    return 0;
}

你实际上可以采用一个类似horner的方案,以一种基本的方式使用倒计时

1 + x/1!+ x ^ 2/2 !+ x ^ 3/3 !+…+ x^n/n!= (((((x/n + 1) * x/(n - 1) + 1) * x/(n - 2) +…)* x/1 + 1

    e = 1.0;
    while (n>0){
        e = e*x/n + 1;
        n--;
    }

比较e^x1/(e^-x)对正x的近似的准确性。

探索(e^(x/4))^4以获得更好的准确性