简体   繁体   中英

C program to evaluate e^x

I'm trying to write a C program that will allow me to evaluate e^x, but I am unsure whether I am on the right track. It seems to work ok for lower values of x, but beyond maybe 5 there is too much error. Just wondering if anyone can see where I've gone wrong with my code (or if my code is correct, is it possibly a problem with the PC not being able to deal with large values of n for n!).

Thanks :-)

Wadeford

unsigned int counter1 = 1, counter2 = 1, counter3 = 1, num, numFactorial, X;
float e, ex, x;

printf( "%s", "Enter a number: ");
scanf( "%d", &num);

printf( "%s", "Enter a value for x: ");
scanf( "%f", &x);

e = e + 2;
counter3 = num;

while ( counter3 > 1 ) {

    counter1 = counter3;
    numFactorial = counter3;
    X = x;

    while( counter1 > 1 ) {
        numFactorial = numFactorial * ( counter3 - counter2);
        counter1--;
        counter2++;
        X = X * x;
    }    
    counter2 = 1;
    e = e + ( 1 / (float) numFactorial );
    ex = ex + X * ( 1 / (float) numFactorial );
    counter3--;
}    

ex = ex + x + 1;

printf( "e to the nth order of approximation (n = %d) is: %f", num, e);
printf( "\ne^x to the nth order of approximation (n = %d) is: %f", num, ex);

I just tried your code, with x=3 it works up to num=19 (so 19th order in the expansion). After that the quantities diverge from their expected value. That's a problem of overflow, your numbers are too big.

If I understand correctly you want to obtain the value for the Neper number and the exponential of a given number x up to a given order (num) in both series expansions.

And you do that calculating the factorial num! inside your code. This should not work with numbers greater than about 15, if numfactorial is an unsigned int. Just because of the representation of the numbers. Use double, at least.

From my experience, when you need to calculate factorials, if that's what you are trying to do, use the Gamma Function , that is in the library "math.h" and it's called tgamma. If you look at the wikipedia page of the Gamma Function, you can use it to obtain the factorial of integer numbers: num! = tgamma(num+1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM