Search code examples
cmathdouble

Function e^x returns 'inf' as output when x is larger then 0.6


I tried to implement this code and it works to a certain point (x<0.6). I am just wondering why it ouputs 'inf' although the stop criteria should terminate the program when it reaches the maximum accuracy of double.

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

double fak(int n) {
    int f = 1;
    int i = 0;
    
    do {
        i++;
        f *= i;
    } while(i<n);
    
    return f;
}

double func_e() {
    double res = 0;
    double res_old = 0;
    double x, k;
    x = 1;
    k = 0;
    
    do {
        res_old = res;
        res += ((pow(x,k)) / fak(k));
        k++;
    } while(res != res_old);
    
    return res;
}

int main(void) {
    //printf("power %f", pow(3,3));
    
    printf("%f", func_e());
    //printf("%f", fak(3));
    
    printf("\n");
    return 0;
}

Solution

  • Check the return value of your function fak. It will overflow and at a certain point return 0. The division by 0.0 results in inf.

    When I modify function fak as

    double fak(int n) {
        int f = 1;
        int i = 0;
        
        do {
            i++;
            f *= i;
        } while(i<n);
        
        printf("fak(%d) = %d\n", n, f);
        return f;
    }
    

    and run it on https://onlinegdb.com/ZxaXfI5xcG, the output is

    fak(0) = 1
    fak(1) = 1
    fak(2) = 2
    fak(3) = 6
    fak(4) = 24
    fak(5) = 120
    fak(6) = 720
    fak(7) = 5040
    fak(8) = 40320
    fak(9) = 362880
    fak(10) = 3628800
    fak(11) = 39916800
    fak(12) = 479001600
    fak(13) = 1932053504
    fak(14) = 1278945280
    fak(15) = 2004310016
    fak(16) = 2004189184
    fak(17) = -288522240
    fak(18) = -898433024
    fak(19) = 109641728
    fak(20) = -2102132736
    fak(21) = -1195114496
    fak(22) = -522715136
    fak(23) = 862453760
    fak(24) = -775946240
    fak(25) = 2076180480
    fak(26) = -1853882368
    fak(27) = 1484783616
    fak(28) = -1375731712
    fak(29) = -1241513984
    fak(30) = 1409286144
    fak(31) = 738197504
    fak(32) = -2147483648
    fak(33) = -2147483648
    fak(34) = 0
    fak(35) = 0
    inf
    

    This means your loop ends when both res and res_old have the value inf.


    Additional remark:

    In func_e you use double k; and pass this to double fak(int n) which converts the value to int. Function fak does the calculation in int and implicitly converts the result to double in the return statement.

    I suggest to avoid these conversions. (Or at least think about the possible problems.) The compiler may warn about this if you enable all warnings.