HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Implementation of exp function in C using Taylor Series expansion

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
expansiontaylorseriesexpfunctionusingimplementation

Problem

I am trying to write code to calcultate ex using:

$$e^x = \sum_{n=0}^\infty \frac{x^n}{n!} = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \cdots $$

This is the code I have, which works for small values of x.
Please do not pay attention to the variable e, specifically to the fact that user enters it.

#include 
#include 

int main(void) {
    double x0,x1,e,x,sum=0.0;
    int n=0;
    scanf("%lf %lf",&x,&e);
    x1=1;
    do{
        sum+=x1;
        x0=x1;
        x1=(x/++n)*x0;
    }
    while(x1/x0>e);

    printf("sum=%lf, \nexp=%lf",sum,exp(x));
    return 0;
}


For input 50 0.00001 number of decimal places for e doesn't matter.
it generates:

sum=5184705528587076239360.000000, 
exp=5184705528587072045056.000000


For input 21 0.00000001:

sum=1318815734.483214, 
exp=1318815734.483215


The difference only increases as x increases.
I assume that condition is wrong but see no other way of doing it.

Solution

Termination condition not correct

To get the precision you request, you should stop the loop when x1 <= e, not when x1 / x0 <= e. If you do that, you can now get rid of x0 because it no longer serves a purpose. I adjusted your program to use the new termination condition and it gave me the results I believe you are looking for. I also renamed e to precision because it was confusing for a variable to be named e when it didn't actually hold the value of the constant \$e\$.

#include 
#include 

int main(void) {
    double x1,precision,x,sum=0.0;
    int n=0;
    scanf("%lf %lf",&x,&precision);

    // Sums: 1 + x + x^2/2! + x^3/3! + x^4/4! + x^5/5! + ...
    //
    // To get an approximation of e^x.
    //
    // Stops when the next term to add becomes smaller than precision.
    x1=1;
    do {
        sum += x1;
        x1  *= (x/++n);
    } while (x1 > precision);

    printf("sum=%lf,\nexp=%lf\n",sum,exp(x));
    return 0;
}

Code Snippets

#include <stdio.h>
#include <math.h>

int main(void) {
    double x1,precision,x,sum=0.0;
    int n=0;
    scanf("%lf %lf",&x,&precision);

    // Sums: 1 + x + x^2/2! + x^3/3! + x^4/4! + x^5/5! + ...
    //
    // To get an approximation of e^x.
    //
    // Stops when the next term to add becomes smaller than precision.
    x1=1;
    do {
        sum += x1;
        x1  *= (x/++n);
    } while (x1 > precision);

    printf("sum=%lf,\nexp=%lf\n",sum,exp(x));
    return 0;
}

Context

StackExchange Code Review Q#123970, answer score: 2

Revisions (0)

No revisions yet.