Hello to all.

I am trying to get an aproximation of expodential of x, using the power serie expansion which is x to the power n over n factorial, with n approaching to inifinty.

Now I am trying to get the value of expodential of 1 by passing to the command line x = {"1.0"},with n ={"25"}. However, I always get 2 as output, instead of a nice 2.7.......
why is that?

Have a look at the code:

public class Exponent {

     
     public static void main (String[] args) {
         double x = Double.parseDouble(args [0]); // command     
         int n = Integer.parseInt(args [1]);  // command   
         
         System.out.println(factorial(n));
         long result = 0;
         
         for (int i = 0; i <= n; i++) {
                result += power(x,i) / factorial(i);
            }
         
         
         System.out.println(result);
         
        }
       
     public static long factorial (int n) { // I used long just becuase the int breaks too soon (@ 15) even with long, 25 is the max number we can compute.
            long result = 1;
            for (int i = 1; i <= n; i ++) {
                result *= i;
            }
            return result;
        }
        
     public static long power (double x, int n) { // also for maximum precision, I used a long for return.
         long result = 1;
            
         for (int i = 1; i <= n; i++) {
             result *= x;
            }
            
            return result;
        }
}

Thank you for your time.

---
Oppression.

Your problem is that you are using 'long' type where 'double' is desirable. For e.g. what should be power of 10.1^2 ? What does your invocation of 'power(10.1, 2)' print? Your power method is broken but it doesn't throw a compile time error because of your use of `*=` construct. Try replacing it with `result = result * x` and you'll notice where you are going wrong.

Your problem is that you are using 'long' type where 'double' is desirable. For e.g. what should be power of 10.1^2 ? What does your invocation of 'power(10.1, 2)' print? Your power method is broken but it doesn't throw a compile time error because of your use of `*=` construct. Try replacing it with `result = result * x` and you'll notice where you are going wrong.

Yes, that solved the problem. Now I have a lovely approximation of e.

The long variables have betrayed my trust and will be annihilated.

-Rides a tank, goes to LongVille and runs over the houses and the peasants who dared defy my unquestionable reign.-

Edited 5 Years Ago by Oppression: n/a

This question has already been answered. Start a new discussion instead.