Project 3: The Ballistics Computer (Trigonometry Simulator)

Build a deterministic projectile-motion simulator that predicts trajectory, flight time, range, and max height from launch conditions.

Quick Reference

Attribute Value
Difficulty Beginner (Level 1)
Time Estimate 8-14 hours
Main Programming Language Python
Alternative Programming Languages JavaScript, C++
Key Topics Trigonometry, vectors, kinematics, numerical simulation
Input Mode CLI launch parameters (speed, angle, height, gravity, timestep)
Output Mode Deterministic metrics + trajectory sample report
Deterministic Requirements Fixed units, fixed gravity default, fixed rounding, fixed timestep policy

1) Learning Objectives

By the end of this project, you should be able to:

  1. Decompose launch velocity into horizontal and vertical components with sine/cosine.
  2. Apply constant-acceleration equations to predict position as a function of time.
  3. Compute time-of-flight, range, and maximum height correctly for baseline projectile model.
  4. Distinguish analytic solution outputs from time-step simulation outputs.
  5. Build deterministic CLI reports that are physically interpretable and testable.
  6. Explain where the simplified no-drag model is valid and where it breaks.

2) All Theory Needed (Per-Concept Breakdown)

Concept A: Vector Decomposition with Trigonometry

Fundamentals

Projectile launch conditions are naturally vector quantities. A speed and angle define a velocity vector that can be decomposed into orthogonal components: horizontal (v_x) and vertical (v_y). Using radians internally is essential for most programming math libraries. If angle is measured from horizontal, then v_x = v0*cos(theta) and v_y = v0*sin(theta). This conversion is the bridge between trigonometry class and motion simulation.

Definitions and key terms

  • Velocity vector: Direction + magnitude of motion.
  • Horizontal component (v_x): Velocity along x-axis.
  • Vertical component (v_y): Velocity along y-axis.
  • Launch angle: Measured from positive x-axis unless otherwise documented.

Mental model diagram (ASCII)

          v0
        / |
       /  | v_y = v0*sin(theta)
      /theta
-----/------------------> x
   v_x = v0*cos(theta)

How it works (with failure modes)

  1. Read speed and angle input.
  2. Convert angle degrees to radians.
  3. Compute v_x and v_y.
  4. Feed components into kinematics equations.

Failure modes:

  • Forgetting degree-to-radian conversion.
  • Swapping sine and cosine roles.
  • Misdefining angle relative to vertical instead of horizontal.

Minimal concrete example (pseudocode)

theta_rad = theta_deg * pi / 180
v_x = v0 * cos(theta_rad)
v_y = v0 * sin(theta_rad)

Common misconceptions

  • At 45 degrees, components are equal only when measured from horizontal.
  • A larger launch angle does not always mean longer range.

Concept B: Constant-Acceleration Projectile Equations

Fundamentals

In the simplified model, horizontal acceleration is zero and vertical acceleration is constant -g. Therefore:

  • x(t) = x0 + v_x*t
  • y(t) = y0 + v_y*t - 0.5*g*t^2

This produces a parabola in the x-y plane. Time-of-flight is found by solving y(t)=0 for the positive time root. Maximum height occurs when vertical velocity becomes zero (v_y - g*t = 0).

Definitions and key terms

  • Gravity g: Constant downward acceleration (default 9.81 m/s^2).
  • Time-of-flight: Time from launch until ground impact (y=0).
  • Range: Horizontal distance at impact.
  • Apex/max height: Highest y-value reached.

Mental model diagram (ASCII)

y
^                 * apex
|              *
|           *
|        *
|     *
|  *
+-----------------------------> x
launch (x0,y0)          impact (range,0)

How it works

  1. Compute velocity components.
  2. Solve y(t)=0 using quadratic formula and keep positive root.
  3. Compute range from x(t_impact).
  4. Compute apex at t_peak = v_y/g if v_y > 0.

Failure modes:

  • Selecting negative quadratic root.
  • Using g sign inconsistently between formulas.
  • Assuming symmetric trajectory when y0 != 0.

Minimal concrete example (pseudocode)

# y(t)=y0 + v_y*t - 0.5*g*t^2 = 0
t_impact = (v_y + sqrt(v_y^2 + 2*g*y0)) / g
range = v_x * t_impact
max_height = y0 + (v_y^2)/(2*g)

Common misconceptions

  • 45 degrees maximizes range only when launch/landing heights are equal and drag is ignored.
  • Horizontal velocity does not decrease in the no-drag model.

Concept C: Time-Step Simulation vs Closed-Form Analytics

Fundamentals

Even when closed-form formulas exist, sampling trajectory points over time is useful for visualization and debugging. A simulator often computes exact summary metrics analytically, then emits sampled trajectory points for plotting. Timestep dt controls trajectory smoothness and data size. Deterministic simulation uses fixed dt, fixed stop condition, and fixed rounding rules.

Definitions and key terms

  • Timestep (dt): Time increment between trajectory samples.
  • Numerical drift: Accumulated error from repeated floating-point updates.
  • Stop condition: Rule for ending simulation (for example, first non-positive y after launch).
  • Interpolation at impact: Estimate exact impact x between last positive and first non-positive sample.

Mental model diagram (ASCII)

t=0    t=dt   t=2dt  ...  t=n*dt
 *  ->   *  ->   *  -> ... -> *
(points approximate continuous parabola)

How it works

  1. Start at (x0,y0).
  2. Advance time by fixed dt.
  3. Compute x(t), y(t) from formulas (avoid accumulating velocity error in beginner version).
  4. Stop when y crosses below zero.
  5. Interpolate impact point for cleaner range report.

Failure modes:

  • Terminating too late and reporting negative final altitude as impact point.
  • Step-size-dependent “range” inconsistencies with no interpolation.

Minimal concrete example (pseudocode)

for t in [0, dt, 2dt, ...]:
  x = x0 + v_x*t
  y = y0 + v_y*t - 0.5*g*t*t
  if y < 0:
    break

Common misconceptions

  • Smaller dt always needed for summary metrics; analytic formulas already provide exact baseline in this model.
  • Simulation points are not required for computing peak analytically.

Concept D: Modeling Assumptions and Validity Boundaries

Fundamentals

A good simulator states assumptions clearly. This project assumes no air resistance, constant gravity, no wind, point-mass projectile, flat landing surface at y=0. These assumptions are acceptable for learning trigonometry and kinematics, but they do not capture real ballistics with drag, spin, density changes, or terrain.

Definitions and key terms

  • Ideal projectile model: Simplified physics with constant gravity and no drag.
  • Drag: Resistive force usually proportional to speed or speed squared.
  • Calibration: Matching model outputs to real-world measurements.
  • Model error: Difference between predicted and observed behavior.

Mental model diagram (ASCII)

Ideal model inputs -> equations -> clean parabola
Real world inputs  -> +drag +wind +spin +terrain -> non-parabolic deviations

How it works

  1. Define assumptions in README and CLI help.
  2. Compute ideal outputs.
  3. Flag that outputs are educational approximations.
  4. Optionally compare to drag-enabled extension later.

Failure modes:

  • Presenting ideal results as real-world precision.
  • Mixing units (meters vs feet) without explicit conversion policy.

Minimal concrete example (pseudocode)

if units == "metric": g = 9.81
if units == "imperial": g = 32.174
# never mix values across systems in same run

Common misconceptions

  • “Simulator is wrong” when real trajectory differs due to ignored drag.
  • Unit mistakes often look like severe physics bugs.

3) Project Specification

3.1 Functional Requirements

  1. Accept launch parameters: speed, angle, initial height, gravity, timestep.
  2. Compute and report:
    • Horizontal velocity component.
    • Vertical velocity component.
    • Time-of-flight.
    • Maximum height.
    • Impact range.
  3. Generate trajectory sample points for plotting/reporting.
  4. Detect invalid input ranges and return clear errors.
  5. Output deterministic report with fixed field order and precision.

3.2 Non-Functional Requirements

  • Performance: Up to 10,000 trajectory points generated under 300 ms on typical laptop.
  • Reliability: Negative speed, zero/negative gravity, and invalid angles handled safely.
  • Usability: All numeric outputs include units.
  • Determinism: Same inputs always yield same rounded values and same sample count policy.

3.3 Example I/O Contract

Input:

--speed 30
--angle-deg 45
--height 0
--gravity 9.81
--dt 0.05
--precision 4

Output (success):

STATUS: OK
INPUT_UNITS: metric
VX: 21.2132 m/s
VY: 21.2132 m/s
TIME_OF_FLIGHT: 4.3248 s
MAX_HEIGHT: 22.9358 m
RANGE: 91.7431 m
TRAJECTORY_POINTS: 88
EXIT_CODE: 0

Output (failure):

STATUS: ERROR
ERROR_CODE: INVALID_INPUT
MESSAGE: speed must be > 0 and gravity must be > 0.
EXIT_CODE: 2

3.4 Edge Cases and Expected Behavior

  1. speed <= 0 -> invalid input error.
  2. gravity <= 0 -> invalid input error.
  3. angle=90 -> near-zero range, vertical shot.
  4. angle<0 with height=0 -> immediate impact (t=0, range=0).
  5. Very high initial height -> long flight; no overflow or crash.
  6. Very coarse dt -> warn about low-resolution trajectory points.

3.5 Real World Outcome (Deterministic Transcript)

How to run

$ python3 p03_ballistics_simulator.py --speed 30 --angle-deg 45 --height 0 --gravity 9.81 --dt 0.05 --precision 4

Golden path transcript (success)

$ python3 p03_ballistics_simulator.py --speed 30 --angle-deg 45 --height 0 --gravity 9.81 --dt 0.05 --precision 4
STATUS: OK
INPUT_UNITS: metric
VX: 21.2132 m/s
VY: 21.2132 m/s
TIME_OF_FLIGHT: 4.3248 s
MAX_HEIGHT: 22.9358 m
RANGE: 91.7431 m
TRAJECTORY_POINTS: 88
IMPACT_POINT: (91.7431, 0.0000)
EXIT_CODE: 0

Failure transcript

$ python3 p03_ballistics_simulator.py --speed -10 --angle-deg 30 --height 0
STATUS: ERROR
ERROR_CODE: INVALID_INPUT
MESSAGE: speed must be > 0 and gravity must be > 0.
EXIT_CODE: 2

4) Solution Architecture

4.1 High-Level ASCII Diagram

CLI Inputs
   |
   v
+----------------------+
| Parameter Validator  |
+----------------------+
   |
   v
+----------------------+      +----------------------+
| Trig Decomposer      | ---> | Analytic Solver      |
| (vx, vy)             |      | (time, range, apex)  |
+----------------------+      +----------------------+
             \                      /
              \                    /
               v                  v
               +----------------------+
               | Trajectory Sampler   |
               | (x(t), y(t), stop)   |
               +----------------------+
                          |
                          v
               +----------------------+
               | Reporter / Formatter |
               +----------------------+

4.2 Key Components

Component Responsibility Notes
Input Validator Enforce valid physical parameters and units Reject impossible configurations early
Trig Decomposer Convert speed+angle into components Uses radians internally
Analytic Solver Compute exact baseline metrics Source of truth for summary values
Trajectory Sampler Generate points by fixed timestep Optional interpolation at ground crossing
Reporter Emit deterministic, unit-labeled output Supports transcript-based grading

4.3 Algorithm Overview

Conceptual pseudocode:

validate(speed, angle, gravity, dt)
(vx, vy) = decompose(speed, angle)
flight_time = positive_root_of(y0 + vy*t - 0.5*g*t^2 = 0)
range = vx * flight_time
max_height = y0 + (vy^2)/(2*g) if vy > 0 else y0
points = sample_trajectory(vx, vy, y0, g, dt)
print deterministic report

Complexity:

  • Analytic metrics: O(1)
  • Sampling: O(T/dt) points where T is flight time
  • Space: O(T/dt) if storing all points

5) Implementation Guide

5.1 Setup

$ cd project_based_ideas/MATH/LEARN_HIGH_SCHOOL_MATH_WITH_PYTHON
$ python3 --version
Python 3.10+ required
$ mkdir -p p03_ballistics_simulator/{artifacts,tests,fixtures}

5.2 Suggested Project Structure

p03_ballistics_simulator/
  artifacts/
    trajectories/
  fixtures/
    golden_cases.txt
    invalid_cases.txt
  tests/
    physics_cases.md
    formatting_cases.md
  README.md

5.3 Core Question

“How do angle and speed become a measurable path in space, and which parts of that path come from exact math versus numeric approximation?”

5.4 Prerequisites You Should Be Comfortable With

  1. Sine/cosine and degree-radian conversion.
  2. Constant-acceleration kinematics equations.
  3. Quadratic equation root selection.
  4. Basic unit consistency and CLI parameter validation.

5.5 Design Questions

  1. Should summary metrics come from analytic equations, simulation, or both?
  2. How do you ensure the chosen impact time root is physically meaningful?
  3. What rounding policy is clear for humans but stable for tests?
  4. How should units be represented and validated?
  5. How will you handle downward launch from ground level?

5.6 Thinking Exercise (Before Implementation)

Compute by hand for v0=30 m/s, theta=45 deg, y0=0:

  1. v_x, v_y
  2. time_of_flight
  3. range
  4. max_height

Questions:

  1. Why are two time roots possible for the quadratic equation?
  2. Which root is physically meaningful and why?
  3. How would results change if g were lower (for example, Moon gravity)?

5.7 Interview Questions

  1. Why does the no-drag projectile path form a parabola?
  2. Under what assumptions is 45 degrees optimal for range?
  3. How do you choose the correct root of the flight-time equation?
  4. What is the trade-off between analytic and timestep simulation?
  5. How would you extend this to include quadratic drag?

5.8 Hints in Layers

  • Hint 1: Implement analytic metrics first and confirm one known case.
  • Hint 2: Add timestep sampling using exact position formulas at each sampled time.
  • Hint 3: Add impact interpolation to reduce timestep-dependent range error.
  • Hint 4: Add deterministic formatting and failure-mode transcripts.

5.9 Implementation Phases

Phase 1 (2-3 hours): Input validation + trig decomposition.

Phase 2 (2-3 hours): Analytic solver for time/range/max height.

Phase 3 (2-3 hours): Trajectory sampler and impact interpolation.

Phase 4 (1-3 hours): Error handling, deterministic output, and test matrix.

5.10 Key Implementation Decisions

Decision Options Recommended Choice Rationale
Summary metric source timestep-only, analytic-only, hybrid hybrid Analytic accuracy + sampled visualization
Angle input radians, degrees degrees input + internal radians User-friendly with clear conversion
Trajectory stop first y<0, exact root solve first y<0 + interpolation Stable and practical
Unit support metric only, metric+imperial metric first Keeps beginner complexity manageable

6) Testing Strategy

6.1 Test Categories

Category Purpose Sample
Unit Validate formulas and root selection known closed-form cases
Integration End-to-end CLI reports compare full transcripts
Edge Invalid physics inputs and corner angles negative speed, 90 deg, negative angle
Regression Prevent output drift golden transcript snapshots

6.2 Critical Test Cases

  1. v0=30, theta=45, y0=0, g=9.81 -> known baseline metrics.
  2. theta=90 -> range approximately zero.
  3. theta=0, y0=0 -> immediate impact behavior.
  4. y0>0 -> asymmetric ascent/descent and longer flight.
  5. speed<=0 or g<=0 -> invalid input exit 2.
  6. Repeat identical input 10 times -> identical output text.

6.3 Deterministic Test Data

default gravity=9.81 m/s^2
default dt=0.05 s
precision=4 decimals
field order fixed

7) Common Pitfalls & Debugging

Pitfall Symptom Debugging Approach Fix
Degree/radian mismatch Outputs wildly off expected values Print theta in degrees and radians before trig Always convert once at input boundary
Wrong root for impact time Negative or impossible flight time Log both roots and selection rule Keep largest positive root
Inconsistent gravity sign Path curves upward or never lands Print equation terms and sign convention in logs Standardize y(t)=y0+vy*t-0.5*g*t^2
Timestep-only range error Range changes too much with dt Compare analytic range vs sampled impact Use interpolation and analytic summary

8) Extensions & Challenges

Beginner:

  • Add optional ASCII trajectory preview in terminal.
  • Add batch mode to compare multiple launch angles.

Intermediate:

  • Add configurable planetary gravity presets (Earth, Moon, Mars).
  • Add obstacle collision detection in 2D.

Advanced:

  • Add drag force model (dv/dt coupled equations).
  • Add target-optimization mode: compute angle/speed combinations to hit a point.

9) Real-World Connections

  • Sports analytics: Ball and projectile trajectory estimation.
  • Robotics and control: Planning ballistic throws or launch arcs.
  • Defense and aerospace foundations: Introductory ballistic modeling before drag/wind complexity.
  • Interview relevance: Demonstrates applied trigonometry, physics modeling, and robust simulation design.

10) Resources

  • “Precalculus” by James Stewart - trigonometric foundations.
  • “Physics for Scientists and Engineers” by Serway and Jewett - projectile motion basics.
  • “Classical Mechanics” by John R. Taylor - deeper motion modeling and assumptions.
  • Python documentation (math) - trig functions and constants.

11) Self-Assessment Checklist

  • I can derive v_x and v_y from speed and angle without notes.
  • I can explain and solve the flight-time quadratic correctly.
  • I can justify which outputs are exact vs timestep approximations.
  • My simulator handles invalid inputs with clear deterministic errors.
  • My baseline case matches expected deterministic transcript.
  • I can explain limitations of the no-drag model in real contexts.

12) Submission/Completion Criteria

Minimum completion:

  • Computes and prints v_x, v_y, flight time, range, and max height.
  • Rejects invalid inputs with exit code 2.
  • Includes one deterministic success transcript.

Full completion:

  • Includes trajectory sampling with documented dt behavior.
  • Includes one deterministic failure transcript.
  • Passes all critical tests listed in this guide.

Excellence:

  • Includes at least one advanced extension (drag, target optimization, or obstacle interactions).
  • Includes concise design note explaining model assumptions and trade-offs.