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
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)));
}
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
.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With