rickylance
rickylance

Reputation: 67

Getting an incorrect output for e^x function I made for class, and getting the wrong number of terms

So for my Intro to computer programming class we have to write 3 separate functions, one to calculate factorials, one to calculate powers (x^n), and one to calculate the number of terms of the taylor series with the given error approximation. Everytime I run my program, it prints that Nterms=1, instead of like 100, 300, 1000, etc.

It's probably a simple error in my loop, but I can't locate it. Any help is appreciated!

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

double power(float A, int B)
{
    double sum=1.00;
    int nterms=1;

    while ( nterms <= B && B > 0) 
    {
        sum = A*sum;
        nterms++;
    }

    return sum; 
}

double factorial(int b)
{
    double fact=1.00;

    while (b >= 2) 
    {
        fact = b*(b-1)*fact;
        b = b-2;
    }

    return fact;    
}

int Terms(float X, float a)
{
    int N=1,l;
    double L,R;



    while (L < a && a <= R)
    {
        l=N+1;
        L= (power(X,l)/(factorial(l)));
        R= (power(X,N)/(factorial(N)));
        N++;
    }

    return N;
}

int main()
{

    float x, delta; 
    double sum=0.00, term=0.00;
    int n, Nterms;


    printf("Please enter a decimal number. x=");
    scanf("%f",&x);
    printf("Please enter an another number. delta=");
    scanf("%f",&delta);


    Nterms=Terms(x,delta);
    printf("Nterms=%d\n",Nterms);

    for(n=0;n<Nterms;n++)
    {
         if( n==0 || n==1 )
        {
            sum = 1 + x;
        }
        else
        {
            sum = sum + term;
            term = (power(x,n))/(factorial(n));
        }   
    }

    printf("The approximation for e^(%f)=%.4f",x,sum);

    return 0;
}

Upvotes: 3

Views: 89

Answers (2)

DrC
DrC

Reputation: 7698

I doubt this is the only problem, but your terms function should probably use a bottom tested loop so that L and R are at least defined. Also, you don't really need to test both L and R as you know L failed to meet the R criteria on the previous iteration. Something like:

int Terms(float X, float a)
{
    int N=0;
    double R;

    do {
        N++;
        R = (power(X,N)/(factorial(N)));
    } while (a <= R)

    return N;
}

Upvotes: 1

Douglas Zare
Douglas Zare

Reputation: 3316

That your Terms function always returns 1 means that N never changes from its initial value, which means that you never enter the while loop

while (L < a && a <= R)

which means that the condition is never satisfied.

I suggest stepping through, noting what you think L and R ought to be when you should require more terms, and checking what they actually are when you get there without initializing them.

Upvotes: 1

Related Questions