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
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.

• 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.