# Approximatio of e

• 07-23-2010, 02:28 PM
java_prgr
Approximatio of e
Ques: Complete the main() method of the Approximation class by
adding code that approximates the number e (the basis of the
natural logarithm). The number e can be approximated by the
following sum: e = (1 / 0!) + (1 / 1!) + (1 / 2!) + (1 / 3!) + ...
– The main() method of the Approximation class asks the user to
enter the number of terms of be computed; your task is to add code
which computes each of these terms and adds them together to form
the approximation of e
• The obvious way of solving this problem involves using
nested loops, where the inner loop computes the required
factorial during every iteration of the outer loop.

herez upto wat i have done:

Code:

```import java.util.Scanner; public class Approximation { public static void main(String[] srgs) {         Scanner keyboard = new Scanner(System.in);                 int n,fact=1;         double e=0;                 System.out.print("Enter the number of terms: ");         n = keyboard.nextInt();                 for(int i=2;i<n;i++){                                 int j;                 for(j =i;j>0;j--){                                                         fact = fact*j;                                                                 }                                                 e = e+(1/(fact));                         }         System.out.print("\ne = "+e);                 } }```
the main prob that i am facing the division as "/" gives only quotient and "%" gives only remainder.

Moderator edit: code tags added
• 07-23-2010, 02:45 PM
Norm
Change the division to be real vs integer. For integer division: 19/10 = 1
Try fact as double vs int
or multiply fact by 1.0 to make the divisor double vs int
• 07-23-2010, 08:30 PM
java_prgr
how can i change the division to be real, can u show me in the code, also do u think my formula is correct for the approximation? as in do they sum up like the equation given in ques??
thnx
• 07-23-2010, 08:35 PM
Norm
What happens when you make fact double?

to convert (fact) to a double, multiply fact by 1.0 (fact*1.0). The compiler will promote the expression's value to type double.

Sorry, I don't know about your formula. Look that up with Google.
• 07-23-2010, 11:10 PM
Fubarable
Your factorial calculation looks a little suspect to me, though I didn't run your code. Myself I'd use either long or BigInteger for the factorial variable since it can get very big quite quickly, and I'd declare it before the loop as you're doing, and then simply multiple it by i once inside a single loop, not a nested loop.

edit: I have tested my code and long works well as long as number of terms is < 67. So no need for BigInteger or BigDecimal.