/* The value e is used to define the "natural logarithm". It is called Euler's number. * Like pi, e is a real number with an infinite number of non-repeating digits. We can * approximate e with the following formula: e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + ... * If we were to write a Java program to compute e, we might think to use doubles which * would limit the precision of our computed e value to that of a double precision float. * Instead, we will use BigDecimal and BigInteger. We need BigInteger to compute large * factorials such as 100! and we need BigDecimal to compute e */ import java.math.*; // for BigInteger and BigDecimal public class ComputeE { public static void main(String[] args) { BigDecimal e=new BigDecimal(0.0); // e will accumulate the sum of 1/i! for an ever increasing i for(int i=0;i<1000;i++) // here, we limit i to be no more than 1000 { BigDecimal temp=new BigDecimal(1.0); // to divide, we need two BigDecimals, the numerator is 1 BigDecimal temp2=new BigDecimal(factorial(i)); // the denominator is i! which we get from calling the factorial method temp2=temp.divide(temp2, 1000, BigDecimal.ROUND_UP); // compute 1/i!, note divide is overloaded, this version is used to // ensure a limit to the iterations when division is limitless like 1/3 e=e.add(temp2); // add the latest 1/i! to e } System.out.println(e); // output our computed e } public static BigInteger factorial(int x) // use a BigInteger for our factorial because int and long are too limited in precision { BigInteger temp=new BigInteger("1"); // start with a BigInteger equal to 1 (note that the constructor requires a String, not an int for(int i=1;i<=x;i++) // iterate x-1 times (we already have the value for 0! (which is 1) temp=temp.multiply(new BigInteger(""+i)); // multiply our BigInteger by the BigInteger obtained with the int value i return temp; } } // run this program and you will get e to 1000 digits: // 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190115738341879307021540891499348841675092447614606680822648001684774118537423454424371075390777449920695517027618386062613313845830007520449338265602976067371132007093287091274437470472306969772093101416928368190255151086574637721112523897844250569536967707854499699679468644549059879316368892300987931277361782154249992295763514822082698951936680331825288693984964651058209392398294887933203625094431173012381970684161403970198376793206832823764648042953118023287825098194558153017567173613320698112509961818815930416903515988885193458072738667385894228792284998920868058257492796104841984443634632449684875602336248270419786232090021609902353043699418491463140934317381436405462531520961836908887070167683964243781405927145635490613031072085103837505101157477041718986106873969655212671546889570351113