简体   繁体   中英

Program that finds certain term in a series for e^x JAVA

My program by first finding a factorial of n form user input. I then take that and perform 1/n to find the term in that location. I then need to add together all the pervious terms to find the approximate value of e at that term in the series.

It prints the right nth term in the series but when i get to adding them together they always come out wrong.

Here is the code to my program:

import java.util.*;

public class Lab01b {

public static void main(String[]args){




    Scanner scan = new Scanner(System.in); // Creates a Scanner object to get input from the user

    double term = -1.0;
    double e = 0.0;  



    /* Loop to recieve user's input */
    while(term < 0){
        System.out.println("Enter factorial number");
        term = scan.nextDouble();
        if(term < 0)
            System.out.println("Enter a number greater than 0");
    }




    e = factorial(term);

    System.out.println("Term: "+term);
    System.out.println("e: "+e);
    System.out.println("Final: "+ e(e, term));





    }


        /*Method to calculate a factorial*/
    public static double factorial(double n){

        double factorial =1;

        for(int i =1; i <= n; i++){

            factorial *= i;

            }

            return factorial;
        }




        /* Method to calculate e^x*/    
    public static double e(double n, double input){


        double factorial = 0.0;
        double counter = 0.0;

        for(int i = 0; i < input+1; i++){

        factorial = 1/n;

        counter += factorial;


        }

        return counter;

    }

}

This is not a programming problem, but a math problem -- you're calculating factoral wrong:

It's not 1 / n , but rather 1 / n! . So your job is to sum the terms of the factoral. I would save the previous factoral so all your loop needs to do is divide it by n. Also, be sure that all your division is double division and not int division, since an int / int will return an int.

Thus 1/20 will return 0 while 1.0 / 20 will return 0.05.

eg,

fact = 1;
sum = 1.0;
for (int i = 1; i < max; i++) {
  fact *= i;
  sum += 1.0 * n / fact;
}

You are counting a factorial wrong, it is 1*2*3...*n, and not 1+2+3...+n!

double factorial = 1.0;
for(int i = 1 ; i <= input ; i++) {
    factorial *= i;
}

Hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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