% Numerically integrate the motion of a ball,
%   in one dimension only (vertical motion)
%   using a constant gravitational force.
%
% The ball starts at ground level, moving vertically
%   upward with some speed.  This initial speed is
%   given as the first argument.
%   
% Use Euler's method to perform numerical integration.
%   The timestep to use in the integratin is given
%   as the second argument.
%
% Print the results to stdout.
%
% Usage:   toss_simple ( initial_speed, timestep )       
%
%   where         initial_speed   is initial speed of ball
%                                    (meters per second)
%
%                 timestep        is the timestep to use in numerical
%                                    integration (seconds)
%
function toss_simple ( initial_speed, timestep )
%
%
% set this to 1 to see diagnostic messages printed as we go
debug = 0;

% constants
%   acceleration due to gravity (m/s^2)
g = 9.8;


if (debug == 1) 
    fprintf(1, 'speed is %f \n', initial_speed);
    fprintf(1, 'timestep is %f \n', timestep);
end


% set the initial position and speed of the ball
%   vertical position (meters)
y = 0;
%   vertical speed (meters per second)
vy = initial_speed;

% set the timestep (seconds)
dt = timestep;
% set the initial time (seconds)
t = 0;

% begin the main loop: move forward by one timestep
%   we quit when the ball's position reaches zero (or becomes negative)
done = 0;
while (done == 0)
    if (debug == 1) 
        fprintf(1, ' t %10.3f  y %10.3f  v %10.3f \n', ...
                 t, y, vy);
    end
    
    % first, we compute the change in velocity
    new_vy = vy - g*dt;
    
    % second, we compute the change in position,
    %   using the new velocity
    %   (this is not the best choice ....)
    new_y = y + new_vy*dt;
    
    if (debug > 0) 
        fprintf(1, ' t %10.3f  new_y %10.3f  new_vy %10.3f \n', ...
                  t, new_y, new_vy);
    end
    
    fprintf(1, ' t %10.3f  y %10.3f  vy %10.3f \n', ...
                  t, y, vy);
              
    % now, we update all the variables to have their new values
    y = new_y;
    vy = new_vy;
    t = t + dt;
    
    % check to see if we should quit
    if (y <= 0)
        done = 1;
    end
   
end


