使用泰勒级数编码 e^x 函数而不使用 math.h 和阶乘函数

coding e^x function using Taylor Series without using math.h and factorial function

我正在制作简单的计算器,它是 e^x 函数部分。

它适用于正数,但不适用于负数 x。 我怎样才能让它也适用于负 x?`

double calculateEx(double x) {
double beforeResult = 1, afterResult = 1, term = 1, error = 1, i = 1, j;

while (error > 0.001) {
    afterResult = beforeResult;
    for (j = 1; j <= i; j++) {
        term *= x;
    }
    term /= fact(i);
    afterResult += term;
    error = (afterResult - beforeResult) / afterResult;
    if (error < 0) error * -1;
    error *= 100;
    beforeResult = afterResult;
    term = 1;
    i++;
}
return beforeResult;

}

double fact (double num) {
int i, j;
double total = 1;

for (i = 2; i <= num; i++) {
    total = total * i;
}
return total;

}

好的,正如我在上面的评论中所写,如果可能的话,我会使用 <math.h>,但既然你问了这个问题:

  1. 为了使其适用于负数,如果 x 为负数,请考虑取反后会发生什么。

  2. 您可以通过存储 table 阶乘来摆脱阶乘函数。您不需要那么多元素。

通过泰勒级数

计算指数
    exp(x) = 1 + x / 1 + x**2/2! + ... + x**n/n!

你不需要任何阶乘,请注意如果n-1第一项是

    t(n-1) = x**(n-1)/(n-1)!

然后

     t(n) = x**n/n! = t(n-1) * x / n;

这就是为什么您需要实施的是:

   double calculateEx(double x) {
     double term = 1.0;
     double result = term;

     /* 
        the only trick is that term can be positive as well as negative; 
        we should either use abs in any implementation or putr two conditions
     */
     for (int n = 1; term > 0.001 || term < -0.001; ++n) {
       term = term * x / n; 

       result += term;
     } 

     return result;
   }