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

StackOverflow https://stackoverflow.com/questions/19416849

  •  01-07-2022
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

You should probably use java.math.BigInteger to store the factorial.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top