Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better approximation of e with Java

I would like to approximate the value of e to any desired precision. What is the best way to do this? The most I've been able to get is e = 2.7182818284590455. Any examples on a modification of the following code would be appreciated.

public static long fact(int x){
    long prod = 1;
    for(int i = 1; i <= x; i++)
        prod = prod * i;
    return prod;
}//fact

public static void main(String[] args) {
    double e = 1;
    for(int i = 1; i < 50; i++)
        e = e + 1/(double)(fact(i));
    System.out.print("e = " + e);
}//main
like image 210
Sharon Avatar asked Sep 26 '09 18:09

Sharon


3 Answers

Use a BigDecimal instead of a double.

BigDecimal e = BigDecimal.ONE;
BigDecimal fact = BigDecimal.ONE;

for(int i=1;i<100;i++) {
  fact = fact.multiply(new BigDecimal(i));

  e = e.add(BigDecimal.ONE.divide(fact, new MathContext(10000, RoundingMode.HALF_UP)));
}
like image 147
Zed Avatar answered Nov 18 '22 22:11

Zed


Your main problem is that double has very limited precision. If you want arbitrary precision, you'll have to use BigDecimal. The next problem you're going to run into is the limited range of long which you're going to exceed very quickly with the factorial - there you can use BigInteger.

like image 44
Michael Borgwardt Avatar answered Nov 18 '22 23:11

Michael Borgwardt


Have you taken a look at the arbitrary-precision arithmetic in java.util.BigDecimal?

import java.math.BigDecimal;
import java.math.MathContext;
public class BigExp {
  public static void main(String[] args) {
BigDecimal FIFTY =new BigDecimal("50");
BigDecimal e = BigDecimal.ZERO;
BigDecimal f = BigDecimal.ONE;
MathContext context = new MathContext(1000);

for (BigDecimal i=BigDecimal.ONE; i.compareTo(FIFTY)<0; i=i.add(BigDecimal.ONE)) {
  f = f.multiply(i, context);
  e = e.add(i.divide(f,context),context);

  System.out.println("e = " + e);
}
  }
}
like image 4
mob Avatar answered Nov 18 '22 21:11

mob