简体   繁体   中英

Java: When dividing by factorials, how do I store the factorial? Its too large to be double

I am new to java, and my program is likely nowhere near as efficient as it could be, but here it is:

public class Compute {
public static void main(String[] args) {
    for(double i = 10000; i <= 100000; i += 10000)
    {
        System.out.println("The value for the series when i = " + i + " is " + e(i));
    }
}
public static double e(double input) {
    double e = 0;
    for(double i = 0; i <= input; i++)
    {
        e += 1 / factorial(input);
    }
    return e;
}
public static double factorial(double input) {
    double factorial = 1;
    for(int i = 1; i <= input; i++)
    {
        factorial *= i;
    }
    return factorial;
}
}

I believe this calculates the value e for i = 10000, 20000, ..., & 100000.
Where e = 1 + (1/1!) + (2/2!) + ... + (1/i!)
It takes about 47 seconds to do so, but I believe it works.

My issue is, for every i, the result is always 0.0
I believe this is because whenever the method factorial is called, the return value is too big to be stored which somehow causes a problem.

What can I do to store the value returned by the method Factorial?

Although you can calculate arbitrary precision results with BigDecimal , there is no need to calculate to 100000! for the series expansion of e . Consider that the 20th term in the series ( 20/20! ) has a magnitude of about 10 -19 , so its contribution to the overall total is insignificant.

In other words, the contribution of any terms after the 20th would change only digits after the 19th decimal place.

您可能应该使用java.math.BigInteger来存储阶乘。

Change this

e += 1 / factorial(input);

to

e += 1 / factorial(i);

Lots to do to speed up the code. Think about (i+1)! vs i!, don't recalc the whole factorial every time.

Also stop calculating when the answer will change less than the required precision like Jim said.

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