Friday, March 6, 2009

Trajectory calculations

Here's a quick snippet of C code that illustrates the algorithm I was talking about today. Some key bits are missing, but it should give you an idea of what to do.

You start with the initial velocity and parameters, and from that calculate everything a time increment dt later. Repeat for many (many) such dt ...

If you don't read C, I can translate it to some other language upon request. If you request something odd like postscript or the like it may take longer ...

Note also that this only calculates the trajectory given some initial inputs. What you want is the launch angle that gives a certain range ... calculating the trajectory is only a portion of that problem.
while (y>=0) {
v = pow((vx*vx)+(vy*vy),0.5);
theta = atan(vy/vx);
ax = ... ; // get these from your force equation
ay = ... ;
vx = vx + ax*dt;
vy = vy + ay*dt;
x = x + vx*dt+0.5*ax*dt*dt;
y = y + vy*dt+0.5*ay*dt*dt;
if (y<0)
y=0; // negative y means we hit the ground
// store various values here
t+=dt;
}

2 comments:

  1. Why in hell would you write this in PostScript? What good does it do to have velocity in points per second?

    ReplyDelete
  2. I wouldn't write it in postscript if I wanted to actually use it. I would write it in C, as I know very well how to optimize C code for numerical performance. I would, however, write it in postscript just to make a point that it can be done in any language you like - the language is largely irrelevant, the algorithm is crucial. You can do this on your TI-89 if you want, it is not computationally demanding.

    If you want to know where the projectile lands, you have to calculate its velocity and position as a function of time, step by step, until your y coordinate reaches zero again (for level ground). Calculating the position at every time requires knowing the velocity at every time, which in turn requires the acceleration. It is a set of coupled non-linear differential equations which have no analytic solution, so you have to do it numerically by starting with your initial conditions, and stepping time forward from there.

    (Of course, if you're referring to the ... in the acceleration formula above, that means you are supposed to fill in that code yourself. The 'points' there are where I deleted my own code.)

    ReplyDelete