【问题标题】:coding e^x function using Taylor Series without using math.h and factorial function使用泰勒级数编码 e^x 函数而不使用 math.h 和阶乘函数
【发布时间】:2017-09-01 05:45:42
【问题描述】:

我正在制作简单的计算器,它是 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;

}

【问题讨论】:

  • 为什么不使用&lt;math.h&gt;exp 函数可能比您可以轻松用 C 编写的任何代码都快(在某些情况下,它可能只是一条机器指令,但至少您可以期望库编写者将其优化为在它生命的一英寸之内)。
  • 小代码审查红旗:你有三个循环。真的有必要吗?
  • 这是我学校的作品,教授命令不要使用 math.h 库。我稍后会在我自己的作品中使用它@alasair
  • @KerrekSB 我将再次检查这三个循环。谢谢你的建议:)

标签: c exponential taylor-series ex


【解决方案1】:

当通过泰勒级数计算指数

    exp(x) = 1 + x / 1 + x**2/2! + ... + x**n/n!

你不想要任何阶乘,请注意如果n-1th 是

    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;
   }

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-01-24
      • 1970-01-01
      • 2014-03-27
      • 2021-02-19
      • 1970-01-01
      • 2021-12-26
      • 2015-07-21
      • 2016-02-01
      相关资源
      最近更新 更多