Search code examples
javaalgorithmapproximation

Trying to approximate the value of natural log e and the number of term use to calculate e


package homework1C;

public class Homework1C {

public static void main(String[] args){
    double term =2,sum;
    int n;
    final double difference = 0.0000000001;
    double x;
    for(sum=0.0,n=0;term > difference;n++){


        x = find_n_fact(n);
        term=1.0/x;
         sum+=term;
         n++;
    }

        System.out.printf("e : %f\n", sum);
        System.out.printf("term : %d\n", n);

    }

public static int find_n_fact(int n){
int i;
int fact = 2;
for(i = n; i>2;i--){

    fact *= i;
}
    return fact;
}

}

this is what i was being asked to do : Write another Java application program to find and display an approximation of e (natural logarithm). Use the following approximation formula starting with n as 2, incrementing by 1 until two successive values of e differ by less than 0.0000000001 and display not only the approximation, but how many terms of n were used in the last approximation. The formula is: approximation of e = 1/0! + 1/1! + 1/2! + 1/3! + ... , where n! is n factorial

This is my present output for this program

e : 1.043081
term : 20

what am i doing wrong ? the answer was suppose to be

e: 2.71828
term: 15

How to solve this?


Solution

  • Several mistakes you have done:

    • Your factorial method was wrong. Although it could be done in iterative manner as you tried, I suggest you the recursive version.
    • You are incrementing n in the for-loop of main() twice, that's nonsense.

    Here is the fully working code for you:

    public class Homework1C {
        public static void main(String[] args) {
            double term = 2, sum = 0;
            final double difference = 0.0000000001;
            int n;
    
            for (n = 0; term > difference; n++) {
                term = 1.0 / find_n_fact(n);
                sum += term;
            }
    
            System.out.printf("e : %f\n", sum);
            System.out.printf("term : %d\n", n);
        }
    
        public static double find_n_fact(int n) {
    
            if (n == 0 || n == 1)
                return 1.0;
    
            return n * find_n_fact(n - 1);
        }
    }
    

    And iterative version of factorial method is here:

    public static double find_n_fact(int n) {
        double i, fact = 1;
    
        if(n < 0) // for negative numbers, factorial is nonsense.
            return -1;
    
        for (i = n; i > 1; i--)
            fact *= i;
    
        return fact;
    }