Search code examples
cexponentialtaylor-seriesex

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


I am making simple calculator and it is e^x function part.

it works for positive number, but it doesn't for negative x. How can I make it works for negative x too?`

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;

}


Solution

  • When computing exponent via Taylor serie

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

    you don't want any factorials, please, notice that if n-1th term is

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

    then

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

    That's why all you have to implement is:

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