简体   繁体   English

用泰勒级数计算任何 x 的 e^x

[英]Computing e^x for any x with Taylor series

I know its pretty bad beginner code but I think it should work, why doesn't it?我知道它非常糟糕的初学者代码,但我认为它应该可以工作,为什么不呢?

It's probably my condidtion haufen != haufen_alt that causes some problems but maybe I'm doing something else wrong.这可能是我的条件haufen != haufen_alt导致了一些问题,但也许我做错了其他事情。

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

double fak(k){
    double i, f_haufen = 1;

    for (i=1; i <= k; i++){
        f_haufen = f_haufen*i;
    }
    return f_haufen;
}

double e_hoch (double x){
    double haufen, haufen_alt, k;

    haufen = 0;
    haufen_alt = 0;
    k = 0;
    do{
        haufen_alt = haufen;
        haufen += (pow(x,k))/(fak(k));
        k++;
    }while(haufen != haufen_alt);

    return haufen;
}

int main (void){
    double x_main;
    printf("x=");
    scanf("%lf", &x_main);

    printf("e^%.2f = %f",x_main, e_hoch(x_main));
}

haufen and haufen_alt will always be different by a nonzero factor of (pow(x,k))/(fak(k)) . haufenhaufen_alt总是会相差一个非零因子(pow(x,k))/(fak(k)) The factor will get smaller and smaller approaching zero, but it won't actually reach zero since the numerator is nonzero.该因子将越来越小,接近零,但实际上不会达到零,因为分子是非零的。

The standard procedure is to decide on some epsilon threshold close to zero you want to stop at.标准程序是确定您想要停止的接近零的某个 epsilon 阈值。 When the next addend drops below epsilon, or when the difference between successive terms is less than epsilon, stop.当下一个加数低于 epsilon 时,或者连续项之间的差小于 epsilon 时,停止。 That lets you tune how accurate you want the result to be.这可以让您调整您希望结果的准确程度。 The smaller epsilon the more accurate it'll be but the longer it'll take. epsilon 越小,它就越准确,但需要的时间越长。

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

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