BallisticMotion.java
Below is the syntax highlighted version of BallisticMotion.java
from §2.4 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[]) {
int WIDTH = 600, HEIGHT = 600;
StdDraw.create(WIDTH, HEIGHT);
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.go(x, y);
StdDraw.spot();
StdDraw.pause(5);
}
StdDraw.show();
}
}
Last updated: Sun Oct 24 22:27:35 EDT 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.