Yash Mathur
Yash Mathur

Reputation: 21

Calculation of e^x without using Math Library

I know that answers to calculation of e^x without using math library are already available.

But I have a small doubt that:

I defined two individual functions: One is power function to evaluate a^b and another factorial function to evaluate n!. I declared these functions to be static so object not required to be created.

Logic Used:

    int l=1; // Declared a variable l and initialised it

    int sum=1;    // The sum variable would be value of e^x

   for(l=1; ; l++)

   {
     sum= sum+ (power(x,l))/(factorial(l)) ; /* Here x is taken as user input and functions are 
                                                 called*/
    }

    System.out.println("The value of e^ "+x +" is " +sum);

  For infinite loop as shown in above code it says unreachable code.
  If i put a condition on l like l<34 then code runs but for l<35 it prints that the value of e^x is infinity.

      So how to get rid of this problem???

Upvotes: 0

Views: 305

Answers (1)

Shpend Palushi
Shpend Palushi

Reputation: 617

I see multiple things going wrong here. First of all calculating the exact value of e is impossible because it is an infinite loop. Secondly all of your variables, probably even those in the functions factorial and power are declared as int, and for sure e is not an int and the calculation does not return an int. Thirdly I don't get the intention of the power function. Fourthly, try separating your problems in smaller ones, an solve them in separate functions. As for calculating the Euler's Constant here is an approach:

public static double calculateE(int noOfCalculations){
    
    double e = 0;
    for(int i=0;i<noOfCalculations;i++) 
        e += (double)1/factorial(i); 
    return e;   
    
}

public static int factorial(int i) {
    if(i==0)
        return 1;
    return i*factorial(i-1);
}

Upvotes: 1

Related Questions