Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Need help with my code (physics pendulum)

  1. #1
    Junior Member
    Join Date
    Jan 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need help with my code (physics pendulum)

    import java.io.*;
     
    public class omg
    {
        // Declare constants 
     
        public static final double DT = 1e-2;    // time interval in seconds
    	public static final double Tmax = 1000.;    // duration of simulation in seconds
     
    	public static final double G = 9.807;    // acceleration due to gravity in m/s/s
    	public static final double M = 1.0;		// Mass of pendulum in kg
    	public static final double L = 9.8;		// Length of pendulum in meter
            public static final double MAXAMPLITUDE =Math.PI  ;//Math.PI;   // Amplitude in rad
    	public static final double DAMPLITUDE = (1.0/100.0);   // Amplitude interval for sampling in rad
            public static final double PRINTAMPLITUDE = 0.20;  // Used to print the time dependant data at a single amplitude value
     
     
        // Start main method
        public static void main(String[] args)
        {
     
    		////////////////////////////////////////////////////////////////
    		//Opening files
    		///////////////////////////////////////////////////////////////
     
    		// Open log file to write the angle vs time data
            PrintWriter outputFile = null;
            try
            {
                outputFile = new PrintWriter(new FileOutputStream("angle_vs_time.txt",false));
            }
            catch(FileNotFoundException e)
            {
                System.out.println("File error.  Program aborted.");
                System.exit(0);
            }
     
    		// Open log file to write the period vs amplitude data
            PrintWriter outputFile2 = null;
            try
            {
                outputFile2 = new PrintWriter(new FileOutputStream("period_vs_amplitude.txt",false));
            }
            catch(FileNotFoundException e)
            {
                System.out.println("File error.  Program aborted.");
                System.exit(0);
            }
     
    		//////////////////////////////////////////////////////////////////////
    		//Starting for real.
    		//////////////////////////////////////////////////////////////////////
     
    		// Calculate length of arrays
    		int imax = (int)(Tmax/DT);		// Maximal index
     
    		// Declare main variables
    		double[] t = new double[imax];		// time in sec
    		double[] angle = new double[imax];	// angular position in radians
    		double[] ang_vel = new double[imax];	// angular velocity in rad/s
    		double[] ang_acc = new double[imax];	// angular acceleration in rad/s/s
    		double[] Etot = new double[imax-1]; 	// Total energy in J
     
    		double amplitude=Math.toRadians(0.25);
    		double cntr;
     
     
    		// Starting the loop that will sample the value of the amplitude
    		for(cntr = DAMPLITUDE; cntr < MAXAMPLITUDE;cntr+=DAMPLITUDE)
    		{
     
    			/////////////////////////////////////////////////////////////////////
    			// Applying Verlet's method to solve the ODE (get angle vs time)
    			/////////////////////////////////////////////////////////////////////
     
    			// Initialize time
    			t[0] = 0;
     
     
    			// We start the pendulum from rest and with its angular position equal to the amplitude
    			angle[0] = amplitude;
    			ang_vel[0] = 0;
     
     
    			// Get the angular acceleration by calling the ang_acceleration method
    			ang_acc[0] = ang_acceleration(angle[0],ang_vel[0],t[0]);
     
     
     
    			// Remember, for Verlet, we need the previous two points so we
    			// do one step of Euler to get value for i=1
    			t[1] = t[0]+DT;
    			angle[1] = angle[0] + ang_vel[0]*DT;
     
    			ang_acc[1] = ang_acceleration(angle[1],ang_vel[1],t[1]);
     
    			for(int i=2;i<imax;i++) {
     
    				// Update time
    				t[i] = t[i-1]+DT;
     
    				// TASK 5: Update the angular position using Verlet's method
    				angle[i]= (2.0*angle[i-1])-angle[i-2]+(ang_acc[i-1]*DT*DT);
     
     
    				// TASK 6: Update angular velocity
    				ang_vel[i-1]=ang_vel[i-2]+ang_acc[i-2]*DT;
     
    				// Update angular acceleration
    				ang_acc[i]=ang_acceleration(angle[i],ang_vel[i],t[i]);
     
     
    			}
     
    			//////////////////////////////////////////////////////////////////////////////
    			// Print time dependent data for the case where amplitude == PRINTAMPLITUDE
    			//////////////////////////////////////////////////////////////////////////////
    			if(Math.abs(cntr - PRINTAMPLITUDE) < 1e-10)
    			{
    				for(int i=0;i<(imax-2);i+=50) // Only print every 10 points
    				{
    						outputFile.println(t[i] + "	" + angle[i] + "	" + ang_vel[i] +
    											"	" + ang_acc[i] + "	");
    				}
    			}
     
     
    			//////////////////////////////////////////////////////////////////////////////
    			// Find and then print period as a function of amplitude
    			//////////////////////////////////////////////////////////////////////////////
     
    			// BONUS TASK (ONLY DO IF YOU'RE DONE WITH EVERYTHING)
    			// Find a better way to get the period from the angle data.
     
    			// Look for two consecutive times when the angle is zero. That correspond to half a cycle.
    			int j = 0; 		 // Index looping over time
    			double angleIsZero = 0; // Storing the time when angle is zero
     
    			while(angleIsZero == 0)
    			{
    				// If the angle switch sign
    				if(angle[j]*angle[j+1]<0){
    					// Choose the angle with the smallest magnitude
    					angleIsZero = Math.abs(angle[j]) < Math.abs(angle[j+1]) ? t[j]:t[j+1];
    				}
    				j++;
    			}
     
    			double angleIsZeroNext = 0; // Storing the next time when angle is zero
     
    			while(angleIsZeroNext == 0)
    			{
    				// If the angle switch sign
    				if(angle[j]*angle[j+1]<0){
    					// Choose the angle with the smallest magnitude
    					angleIsZeroNext = Math.abs(angle[j]) < Math.abs(angle[j+1]) ? t[j]:t[j+1];
    				}
    				j++;
    			}
     
    			// The 2* below is needed because we have the time difference for half a cycle.
    			outputFile2.println(amplitude + "	" + 2*(angleIsZeroNext-angleIsZero));
     
     
    		}
     
    		///////////////////////////////////////////////////////////////////////
    		// Closing files
    		///////////////////////////////////////////////////////////////////////
    		outputFile.close();
    		outputFile2.close();
        }
     
    	////////////////////////////////////////////////////////////////////////////
    	// Method calculating the angular acceleration
    	////////////////////////////////////////////////////////////////////////////
    	public static double ang_acceleration(double angle, double angvel,double time)
        {
    		double ang_accel;
    		double q, dt, omega,  drivingForce=0.5;
    		q=0.5;
    		dt=0.01;
    		omega=2.0/3.0;
     
     
     
    		// TASK 4: Write the equation for the angular acceleration
    		ang_accel= (-G/L)*Math.sin(angle)-q*angvel+(drivingForce*Math.sin(omega*time));
     
     
    		return ang_accel;
        }
     
    }

    The main part of the program is the method listed at the bottom.I've done all i could think of but i still get an error for an array that is out of bounds...The program basically simulates the movement of a pendulum,the ang_acceleration method calculates the angular acceleration and the for loop loops for every single array index. You guys can ignore the part where it says //BONUS.
    is there something wrong with my initial for loop?I had an earlier version of this code with a simplified ang_acceleration method that only had one variable called to it and it was working perfectly.Sorry if this sounds way too specific.Ask questions if needed and I will try to answer as best as i can.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help with my code (physics pendulum)

    get an error for an array that is out of bounds
    Check the statement where that happens and see why the value of the index is out of bounds for the array that is being indexed.
    Remember array index values range from 0 to the array length-1
    The max index for an array with 5 elements would be 4

    Post the full text of the error message if you need help with it.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with my code (physics pendulum)

    Hey thanks for your reply,Norm.So its kind of odd but I only get an out of bounds error when I change the drivingForce to anything but zero,my code works when its zero but i get an error whenever i try to change it,which is needed for my assignment.Here's the full error when I let the drivingForce be equal to 0.5:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:100000 at pendulum.main<pendulum.java:169>. Does the 169 mean that the error occurs at the 169th iteration of the loop?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help with my code (physics pendulum)

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:100000
    at pendulum.main<pendulum.java:169>
    The 169 is the source line number where the error happened. 100000 is the value of the index???
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jan 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with my code (physics pendulum)

    Yeah..I don't understand what makes that happen though.And its out of bounds in what array?Is there a way to find out?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help with my code (physics pendulum)

    out of bounds in what array?Is there a way to find out?
    It will be one of the arrays on line 169. Add a println just before line 169 and print out all the variables' values and the size of all the arrays used on line 169.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Jan 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with my code (physics pendulum)

    I think I'm stuck in an infinite loop...this is what is written on line 169:

     
     
    if(angle[j]*angle[j+1]<0){
    					// Choose the angle with the smallest magnitude
    					angleIsZeroNext = Math.abs(angle[j]) < Math.abs(angle[j+1]) ? t[j]:t[j+1];
    				}
    				j++;
    			}

    and what happens right before it is
     
    			while(angleIsZeroNext == 0)
     
    			{for (int i=0;i<angle.length;i++)
    				System.out.println(+angle[i]+ang_vel[i]+ang_acc[i]+t[i]+i);

    And that is my loop to print out the values and the size of the array.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help with my code (physics pendulum)

    What variable controls the loop? Where is the value of that variable changed so that the looping can end?
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Jan 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with my code (physics pendulum)

    int j = 0; 		 // Index looping over time
    			double angleIsZero = 0; // Storing the time when angle is zero
     
    			while(angleIsZero == 0)
    			{
    				// If the angle switch sign
    				if(angle[j]*angle[j+1]<0){
    					// Choose the angle with the smallest magnitude
    					angleIsZero = Math.abs(angle[j]) < Math.abs(angle[j+1]) ? t[j]:t[j+1];
    				}
    				j++;
    			}
     
    			double angleIsZeroNext = 0; // Storing the next time when angle is zero
     
    			while(angleIsZeroNext == 0)
     
    			{for (int i=0;i<angle.length;i++)
    				System.out.println(+angle[i]+ang_vel[i]+ang_acc[i]+t[i]+i);
     
    				if(angle[j]*angle[j+1]<0){
    					// Choose the angle with the smallest magnitude
    					angleIsZeroNext = Math.abs(angle[j]) < Math.abs(angle[j+1]) ? t[j]:t[j+1];
    				}
    				j++;
    			}
     
    			// The 2* below is needed because we have the time difference for half a cycle.
    			outputFile2.println(cntr + "	" + 2*(angleIsZeroNext-angleIsZero));
     
     
    		}

    yeah, sorry i guess i'll just post the entire loop here.its comparing values of the angle array.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help with my code (physics pendulum)

    Can you answer these questions?

    What variable controls the loop?

    Where is the value of that variable changed so that the looping can end?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Jan 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with my code (physics pendulum)

    Well the variable that controls the while loop are anlgeIsZero and angleIsZeroNext.As long as they are equal to zero then the loop would continue...angleIsZero and angleIsZeroNext are basically values from the array called angle.So the while loops compare all of the values from the array,finding the smallest value before stopping.That's what I understand from the code.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help with my code (physics pendulum)

    As long as they are equal to zero then the loop would continue
    What will change their value to non-zero? To prevent an infinite loop their value has to be changed.

    If you want to set an absolute limit to the number of times the loop will go around, use a counter variable:
     int count = 0;
     int MaxLoopsCount = <the max number of loops to do>
      while(somecondition && (count++ < MaxLoopsCount)) {
        ...  the loop stuff here
      } // end while loop


    One problem I see with the code in post#9 is missing {}s following the for statement.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 3
    Last Post: January 15th, 2013, 02:18 PM
  2. Replies: 5
    Last Post: November 14th, 2012, 10:47 AM
  3. Simple Game Physics & Animation (Air Hockey)
    By Spaces Allowed? in forum AWT / Java Swing
    Replies: 6
    Last Post: November 2nd, 2011, 04:48 AM
  4. [SOLVED] Physics Program
    By pwngrammer in forum Algorithms & Recursion
    Replies: 36
    Last Post: June 15th, 2009, 08:32 AM