BallisticMotion.java


Below is the syntax highlighted version of BallisticMotion.java from §1.5 Input and Output.


/*************************************************************************
 *  Compilation:  javac BallisticMotion.java
 *  Execution:    java BallisticMotion v theta
 *  Dependencies: StdDraw.java
 *
 *  Simluate the motion of a ball fired with velocity v at theta degrees
 *  with coefficient of drag C. Uses Euler-Cramer method to numerically
 *  solve differential equation.
 *  
 *  % java BallisticMotion 180 60 
 *
 *************************************************************************/

public class BallisticMotion {

   public static void main(String[] args) {
      double G = 9.8;     // gravitational constant m/s^2
      double C = 0.002;   // drag force coefficient

      double v     = Double.parseDouble(args[0]);
      double theta = Double.parseDouble(args[1]);    // read in angle in degrees
      theta = theta * Math.PI / 180.0;               // convert to radians

      double x = 0.0, y = 0.0;           // position
      double vx = v * Math.cos(theta);   // velocity in x direction
      double vy = v * Math.sin(theta);   // velocity in y direction

      double ax = 0.0, ay = 0.0;         // acceleration
      double t  = 0.0;                   // time
      double dt = 0.01;                  // time quantum

      // loop until ball hits ground
      while (y >= 0) {
         v = Math.sqrt(vx*vx + vy*vy);
         ax = -C * v * vx;
         ay = -G - C * v * vy;
         vx += ax * dt;
         vy += ay * dt;
         x  += vx * dt;
         y  += vy * dt;
         StdDraw.point(x, y);
         StdDraw.show(5);
      }
      StdDraw.show();
   }
   
}


Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.
Last updated: Wed Feb 9 09:02:07 EST 2011.