简体   繁体   中英

e^x = 1 + x + x2/2! + x3/3! + x4/4! << e to the x power using java method

So. Hello smart ones. What am I doing wrong here? I just can't figure out what is wrong with this code. 10 points for whomever helps me. I'm trying to use recursion to make a method for e^x. using the e^x = 1 + x + x2/2! + x3/3! + x4/4! + ... e^x = 1 + x + x2/2! + x3/3! + x4/4! + ... e^x = 1 + x + x2/2! + x3/3! + x4/4! + ... equation

public class tester {
    public static double power(double x, int n) {
        if (n == 0) {
            return 1;
        } else {
            return x * power(x, n - 1);
        }

    }

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

    public static double myexp(double x, int n) {
        if (n == 0) {
            return 1;
        } else {
            return (power(x, n) / factorial(n)) + myexp(x, n - 1);
        }
    }

    public static void main(String[] args) {
        System.out.println(myexp(x, n)); // unfortunately, increasing n value
                                            // makes it go infinite.
    }

}

So x is the x in e^x and n is the total value when up to nth term is added. So for example, myexp(3,5) is going to be e^3 added up to 5th term. Thus, the higher the n is, the more accurate e^3 is going to be.

Your problem is the use of the "int" data type for the factorial method. More specifically, factorial numbers quickly become huge and the int data type is too small. For example, if you code:

public static void main(String[] args) {
    System.out.println(factorial(50));
}

The output is 0 which is obviously wrong, hence your result of Infinity . Simply change the return type of factorial from int to double as follows:

public static double factorial(int n)

And then if you try:

public static void main(String[] args) {
    System.out.println(myexp(1., 100));
}

You get 2.7182818284590455

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