简体   繁体   English

评估e ^ x的C程序

[英]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. 我正在尝试编写一个C程序,该程序将允许我评估e ^ x,但是我不确定自己是否走对了。 It seems to work ok for lower values of x, but beyond maybe 5 there is too much error. 对于较低的x值似乎可以正常工作,但是可能超过5则存在太多错误。 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!). 只是想知道是否有人可以看到我的代码哪里出了问题(或者我的代码是正确的,这可能是PC无法处理n大于n的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). 我刚刚尝试了您的代码,当x = 3时,它最多可以达到num = 19(因此在扩展中为19阶)。 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. 如果我理解正确,那么在两个系列扩展中,您都希望获得Neper数的值以及给定数字x的指数,直到给定的阶数(num)。

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. 如果numfactorial是一个无符号int,则此方法不适用于大于约15的数字。 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. 根据我的经验,当您需要计算阶乘时,如果要这样做,请使用库“ math.h”中的Gamma Function ,它称为tgamma。 If you look at the wikipedia page of the Gamma Function, you can use it to obtain the factorial of integer numbers: num! 如果查看Gamma函数的Wikipedia页面,则可以使用它来获取整数的阶乘:num! = tgamma(num+1) = tgamma(num + 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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