如何在c中编写exp(x)代码?

时间:2017-03-09 05:04:19

标签: c recursion exp

有一个exp函数的系列,看起来像这样: exp(x) = (x^0)/0! + (x^1)/1! + (x^2)/2! + (x^3)/3! + ···。而我正在尝试为x的不同值计算它,用计算器检查我的结果,并且我发现对于大值,例如20,我的结果停止增加并且卡在几乎是真实值的值中。我得到485165184.00,实际值为485165195.4

我必须在for循环或递归函数中执行此代码,因为它是一项家庭作业。

我的代码如下所示

#include <stdio.h>
#define N 13
#define xi 3

double fun7(int n, int m){
    int i;
    double res=1, aux=0;
    for(i=1, aux=1; i<(n+1); i++){
    res += aux;
    aux *= m;
    aux /= i;
    }
    return res-1;
}



int main() {
    int a, b, pot, x[xi];
    float R[N][xi];

    x[0] = 5;
    x[1] = 10;
    x[2] = 20;

    for(b=0; b<xi; b++){
        for (a=0, pot=1; a<N; a++){
            R[a][b] = fun7(pot, x[b]);
            pot *= 2;
        }
    }

    for(b=0; b<xi; b++){
        for (a=0, pot=1; a<N; a++){
            printf("%d\t%f\n", pot, R[a][b]);
            pot *= 2;
        }
        printf("\n");
    }

    return 0;
}

1 个答案:

答案 0 :(得分:4)

float数据类型通常可以表示精度超过7位小数的​​数字。

485165184有9位小数。就float而言,最后两位数字只是无意义的噪音。你真的应该显示4.851652e8,它是exp(20)的正确值,具有给定的精度。

如果您想提高精确度,请尝试使用doublelong double数据类型。