Results 1 to 19 of 19
  1. #1
    java157 is offline Member
    Join Date
    Mar 2011
    Posts
    27
    Rep Power
    0

    Default alternating series sum java help

    For my assignment I have to create a program that calculates the following:


    x - x^3/3! + x^5/5! - x^7/7! + ..... + - x^n/n!

    Where the user inputs the value of x they want to calculate and inputs the value of n for the maximum exponent value (the higher the exponent the user inputs the more accurate the calculation will be).

    Here's my attempt to the problem:

    Java Code:
    import java.io.*;
    public class s {
    public static void main(String args[]) throws IOException
    {
    BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in));
    	
    	double x;
    	int n;
    	
    	System.out.print("Input a value for x: ");
    	x = Double.parseDouble(keybd.readLine());
    	
    	System.out.print("Input max exponent: ");
    	n = Integer.parseInt(keybd.readLine());
    	
    	int factorial=1;
    	for (int i=2; i<=n; i++)                // this for loop finds factorials (ie 5!=120)
    	{
    		factorial = factorial * i;
    	}
    	
    	int exp=1;
    	double sum = 0;
    	for (int i=1; i<=n; i=i+2)
    {
    sum = sum + (Math.pow(-1,i))*(Math.pow(x,i))/(factorial); 
    // i don't think I did the factorial part correctly.
    // Also I can't get the alternating between positive and negative. it starts with negative because (-1)^1= -1 but the first term of series has to be positive.
    }
    	
    	System.out.println("The result is: " + sum);
    }
    
    }
    Please help! Thanks!
    Last edited by java157; 03-18-2011 at 11:24 PM.

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    This wont really work easily without a static method to fomput the factorial.

    You can more easily break each expression down to
    Java Code:
    x^((2n + 1)/((2n + 1)!)
    so you would want to do something like
    Java Code:
    Math.pow(x, ((2n + 1)/yourFactorialMethod(2n + 1)));
    I gave you a decent amount here, but I left you with figuring a bit out, create a static factorial class and post the code for it.(start small, work up)

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Does your code compile? If not and you can't understand the messages post them.

    If it runs but the runtime behaviour is not what you expect (ie it gives a strange answer or throws an exception), say what it does.

    And please use code tags: put [code] at the start of your code and [/code] at the end: that way the indentation is preserved.

    -----

    // i don't think I did the factorial part correctly.

    One way to see to to print out the value produced by your factorial loop.

    Java Code:
    int factorial=1;
    for (int i=2; i<=n; i++) // this for loop finds factorials (ie 5!=120)
    {
        factorial = factorial * i;
    }
    [color=blue]System.out.println("n=" + n);
    System.out.println("n!=" + factorial);[/color]

  4. #4
    java157 is offline Member
    Join Date
    Mar 2011
    Posts
    27
    Rep Power
    0

    Default

    Quote Originally Posted by pbrockway2 View Post
    Does your code compile? If not and you can't understand the messages post them.
    code compiles, but does not output correct answer

  5. #5
    java157 is offline Member
    Join Date
    Mar 2011
    Posts
    27
    Rep Power
    0

    Default

    Is it possible to create a for loop within a for loop? Would that work?

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,197
    Rep Power
    19

    Default

    Best way to find out is to try it and see for yourself!

    db

  7. #7
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    By the way, @op, were you able to do the last problem?
    E(2n + 1)!

    If you were this is sort of just a step up from that as I pointed out above.

  8. #8
    java157 is offline Member
    Join Date
    Mar 2011
    Posts
    27
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    I gave you a decent amount here, but I left you with figuring a bit out, create a static factorial class and post the code for it.(start small, work up)
    Is it possible to do this without creating a new class?

  9. #9
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    yes. One class can have many methods, I am wanting you to have one of the methods in the class be a factorial method. Below I have created a static method to print hello.

    Java Code:
    public class StaticHello{
      public static void hello(){
        System.out.println("Hello, World");
      }
      public static void main(String[] args){
        hello();
      }
    }

  10. #10
    java157 is offline Member
    Join Date
    Mar 2011
    Posts
    27
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    yes. One class can have many methods, I am wanting you to have one of the methods in the class be a factorial method. Below I have created a static method to print hello.

    Java Code:
    public class StaticHello{
      public static void hello(){
        System.out.println("Hello, World");
      }
      public static void main(String[] args){
        hello();
      }
    }
    Ok I think I get it now, but under the factorial method it says "the local variable n may not have initialized". Says something similar for FactorialMethod (check comments within the code):

    Java Code:
    import java.io.*;
    public class s{
    public static void main(String args[]) throws IOException
    {
    BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in));
    	
    	double x;
    	int n;
    	
    	System.out.print("Input a value for x: ");
    	x = Double.parseDouble(keybd.readLine());
    	
    	System.out.print("Input max exponent: ");
    	n = Integer.parseInt(keybd.readLine());
    	
    	double sum;
    	for (int i=0; i<=n; i++)
    	{
    		sum += (Math.pow(-1,i))*(Math.pow(x,((2*n + 1))/((2*n + 1)FactorialMethod); // "FactorialMethod cannot be resolved to a variable"
    	}
    	System.out.println("The result is: " + sum);
    }
    
    public static int FactorialMethod;{
    	int n;
    	int factorial=1;
    	for (int i=2; i<=n; i++) //"the local variable n may not have initialized"
    	{
    		factorial *= i;
    	}
    }
    
    }

  11. #11
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    close, to help you out a bit more I will make a static method to determine if a number is prime.

    Java Code:
    public class IsPrime{
      public static boolean isPrime(int n){
        boolean flag = true; //assume the number is prime
        for(int i = 2; i < n; i++){
          if(n % i == 0){//if number is evenly divisble by i, switch flag to false, end loop.
            flag = false;
            break;
          }
        }
        return flag;//return the flag(true if nothing divides evenly into n, otherwise returns false)
      }
      public static void main(String[] args){
        System.out.println(isPrime(10));
        System.out.println(isPrime(11));
      }
    }

  12. #12
    java157 is offline Member
    Join Date
    Mar 2011
    Posts
    27
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    close, to help you out a bit more I will make a static method to determine if a number is prime.

    Java Code:
    public class IsPrime{
      public static boolean isPrime(int n){
        boolean flag = true; //assume the number is prime
        for(int i = 2; i < n; i++){
          if(n % i == 0){//if number is evenly divisble by i, switch flag to false, end loop.
            flag = false;
            break;
          }
        }
        return flag;//return the flag(true if nothing divides evenly into n, otherwise returns false)
      }
      public static void main(String[] args){
        System.out.println(isPrime(10));
        System.out.println(isPrime(11));
      }
    }
    It still says n can't be initialized to a variable:

    Java Code:
    public static int FactorialMethod;{
    	int n;
    	boolean flag = true;
    	int factorial=1;
    	for (int i=2; i<=n; i++) // "n has not been initialized to variable"
    	{
    		if ((n % i == 0)){
    			flag = false;
    	        break;
    		}
    		else
    		{
    		factorial *= i;
    	}
    }
    
    }
    }
    How to I make the n equal to the value that the user inputs into the main method (or whatever it's called :D)

  13. #13
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Your method is incorrect(you don't need a flag to find the factorial)

    The reason I used the flag was to show you a bit more complex example of a static method(one that takes an argument)

    Compare my method declaration and yours

    Mine:
    Java Code:
    public static boolean isPrime(int n)
    yours:
    Java Code:
    public static int FactorialMethod;
    Besides the name and return type there is one major difference. Where does my static method to determine if a number is prime declare n?

  14. #14
    java157 is offline Member
    Join Date
    Mar 2011
    Posts
    27
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    Your method is incorrect(you don't need a flag to find the factorial)

    The reason I used the flag was to show you a bit more complex example of a static method(one that takes an argument)

    Compare my method declaration and yours

    Mine:
    Java Code:
    public static boolean isPrime(int n)
    yours:
    Java Code:
    public static int FactorialMethod;
    Besides the name and return type there is one major difference. Where does my static method to determine if a number is prime declare n?
    Here it says "Syntax error on 'FactorialMethod', delete this token"

    Java Code:
    sum += (Math.pow(-1,i))*(Math.pow(x,2*n + 1))/((2*n + 1)FactorialMethod);
    Also have another error below
    Here it says. "This method must return a result of type boolean"

    Java Code:
     public static boolean FactorialMethod(int n){
    Last edited by java157; 03-19-2011 at 01:24 AM.

  15. #15
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Ill give you the factorial method since you seem to be genuinely trying but I want you to understand how it works, instead of simply copying and pasting it.

    Java Code:
    public static int factorial(int n){  //it's public and static, it returns and int, and takes an int as an argument
      for(int i = n; i > 0; i--){
        sum *= i;
      }
    }
    I left two bugs in the code which will make it not compile, you have to find them(this forces you to think about it instead of copy/pasting).

    Once you find the bugs you want to work on the actual heart of the problem.

    Which really breaks down to
    Math.pow(x, ((2n + 1)/(factorial(2n + 1))));

  16. #16
    java157 is offline Member
    Join Date
    Mar 2011
    Posts
    27
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    Ill give you the factorial method since you seem to be genuinely trying but I want you to understand how it works, instead of simply copying and pasting it.

    Java Code:
    public static int factorial(int n){  //it's public and static, it returns and int, and takes an int as an argument
      for(int i = n; i > 0; i--){
        sum *= i;
      }
    }
    I left two bugs in the code which will make it not compile, you have to find them(this forces you to think about it instead of copy/pasting).

    Once you find the bugs you want to work on the actual heart of the problem.

    Which really breaks down to
    Math.pow(x, ((2n + 1)/(factorial(2n + 1))));
    It took me several hours (looking through tutorials and figuring it out) to get this done. I'm glad you helped me instead of just giving me the answer because I actually learned something. Thank you :)

  17. #17
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Did you get the whole problem solved?

  18. #18
    java157 is offline Member
    Join Date
    Mar 2011
    Posts
    27
    Rep Power
    0

    Default

    Yes. The program works fine and calculates correct answers

  19. #19
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I'm glad you solved it, please mark your your thread solved with the thread tools.

Similar Threads

  1. Alternating Transparency Based on Double Variable
    By YellowPainting in forum Java 2D
    Replies: 2
    Last Post: 11-05-2010, 08:59 PM
  2. Perrin series
    By moamen in forum New To Java
    Replies: 6
    Last Post: 12-04-2009, 05:27 PM
  3. Generating Fibonacci Series with a Multithreaded Java Program
    By firesauce in forum Threads and Synchronization
    Replies: 1
    Last Post: 10-20-2009, 07:26 AM
  4. Alternating Sum
    By ScaryJello in forum New To Java
    Replies: 6
    Last Post: 10-13-2009, 09:18 AM
  5. strange alternating array
    By jarvis in forum New To Java
    Replies: 2
    Last Post: 04-23-2009, 09:42 AM

Posting Permissions

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