1. Member Join Date
Jul 2010
Posts
6
Rep Power
0

## 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:

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

Last edited by Fubarable; 07-23-2010 at 11:04 PM. Reason: code tags added  Reply With Quote

2. ## 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  Reply With Quote

3. Member Join Date
Jul 2010
Posts
6
Rep Power
0

## 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  Reply With Quote

4. ## 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.  Reply With Quote

5. ## 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.
Last edited by Fubarable; 07-23-2010 at 11:25 PM.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•