P00.09 ยท Lesson 09 of 15
Symbolic Math with SymPy
Let the computer do the algebra; keep the physics, and the checking, for yourself.
Build it Derive and lambdify an equation of motion
- Learning outcomes
- Derive the equation of motion of a point mass falling under gravity with quadratic drag, state where it is valid, and find its terminal velocity and exact solution.
- Encode the derivation in SymPy: symbols with assumptions,
Eq,solve,diff,integrate,limit,series,simplify. - Turn a symbolic expression into a fast NumPy function with
lambdifyand check it against hand values, limiting cases and a SciPy integration. - Check a symbolic derivative against a finite difference and explain the error curve (truncation versus rounding).
- Prerequisites
P00.03,P00.06,P00.07; Bridge B1 (algebra, trig); skill check: can differentiate and integrate with a table; knows what an initial condition is.- Engineering question
How fast does a 1.2 kg instrument package fall after release, when does drag stop it accelerating, and how far has it fallen by then?
Full lesson specification (11 more items)
- Assumptions and limits
Point mass; one-dimensional vertical motion with the object never moving upward (); constant gravity ; constant air density and drag coefficient, so is constant; drag exactly quadratic in speed. Fails for a 10 km drop (density changes), near Mach 1 ( changes), at very low speed where drag becomes linear in (Stokes regime), and for a body that tumbles ( and change).
- Analytical work
Separation of variables to the solution; terminal velocity; distance fallen; small-time series; no-drag limit.
- Computational deliverable
starter/main.py:acceleration_expr,terminal_velocity_expr,velocity_expr,position_expr,ode_residual,no_drag_limit,small_time_series,acceleration_derivative_expr, fourlambdify_*functions,central_difference,derivative_check,velocity_derivative_check. Tests prove: the symbolic solution satisfies the ODE identically, , the limit is , the series coefficients are right, lambdified functions match hand values and limits, and the finite-difference check converges at second order.- Practical activity
computational experiment: measure the error of the finite-difference derivative against the symbolic one over eight decades of step size and locate the truncation/rounding crossover.
- Equipment
None
- Safety
None beyond normal computer use. The lesson does not ask you to drop anything; P00.15 does, with its own safety box.
- Evidence
Completed
main.py, passing tests,fall_with_drag.png, the error-versus- table and log-log plot, and a short note explaining the shape of that curve.- Assessment
assessments/phase-00/grading-rubric.md; competencies 1 (reasoning), 2 (analytical), 3 (computational); pass when the derivation is complete with assumptions named, all public tests pass, and the error-curve note identifies both regimes with numbers.- References
@sympy-tutorial"Introductory Tutorial": "Gotchas" (Symbols, Equals signs), "Basic Operations", "Simplification", "Calculus", "Solvers" (required-free);@numpy-userguide"NumPy quickstart" for the arrayslambdifyreturns (supplementary-free).- Extensions
โ Solve the ODE directly with
sp.dsolveand show the result is the sametanh. โ Add the upward-motion branch () withsp.Piecewiseorsp.signand verify againstsolve_ivp. โ Let follow the ISA from P00.03 and show the symbolic approach stops helping.- Time
unmeasured
1. The engineering problem
An instrument package of mass 1.2 kg, frontal area 0.01 mยฒ and drag coefficient about 1.0 is released from a balloon or a slow aircraft. The parachute team needs three numbers before the flight: the speed it will reach if the parachute fails to open (terminal velocity), how long it takes to get there, and how far it falls meanwhile. Those numbers set the opening altitude and the size of the recovery area.
The physics is Newton's second law with two forces. The hard part is not the physics; it is the algebra of solving a non-linear differential equation and then trusting the result. Done by hand, that algebra is where sign errors and lost factors of two live. Done by a computer algebra system, it is fast and exact, but a computer algebra system will happily simplify a wrong equation. So the lesson has two halves: use SymPy (the Python library for symbolic mathematics) to derive and solve, and then use the tools of P00.07 to check the symbolic result against limiting cases, a finite-difference derivative and a numerical integration.
Success criterion: an exact expression for and that satisfies the equation of motion identically (not just numerically), a NumPy function made from it that agrees with scipy.integrate.solve_ivp to better than m/s, and a plot of the three predictions.
2. Understand and derive
2.1 Forces and the equation of motion
Take downward as positive and let be the speed (so while falling). Two forces act: weight downward, and aerodynamic drag opposing the motion, i.e. upward.
Define the drag constant
so . Units: , and has units . Newton's second law:
Assumptions used so far: point mass (no rotation), constant (altitude change small compared with Earth's radius), constant , and (no tumbling, low Mach, altitude change small compared with the atmosphere's scale height of about 8 km), and (if the body could move upward the drag would have to be written ). For the example: kg/m.
2.2 Terminal velocity
Acceleration vanishes when drag balances weight:
Units: . For the example, m/s (158 km/h). Note the scaling: doubling the mass raises by ; doubling the area lowers it by . A 1 kg payload under a 2 mยฒ parachute () has m/s. This is the first limiting case a test should check: exactly.
2.3 Exact solution by separation of variables
Write the equation as , using . Separate:
The left side is a standard integral: for . Hence
Check it: . โ The time constant is (4.5 s for the example): after the speed is 99 % of terminal.
Integrate once more for the distance fallen with :
Check: . โ
2.4 Two more limiting cases and a series
- No drag: as , and , so : free fall. A test asserts
limit(v, k, 0) == g*t. - Long time: , so and : the body falls as if at terminal speed, minus a fixed distance lost while accelerating.
- Small time: with gives
The term is drag's first bite. Its relative size is , so drag changes the speed by 1 % after s for the example. Series like this are how you decide when a simpler model (free fall) is good enough.
2.5 Checking a derivative numerically
If is smooth, the central difference
has truncation error , and rounding error about with . The total is smallest where the two balance, , which is around to for quantities of order one. For , a quadratic, : the central difference is exact up to rounding, so the check in derivative_check measures pure rounding (about ). For , which has non-zero , the error in velocity_derivative_check falls as until rounding takes over. Seeing both behaviours is the point of part 4.
2.6 How SymPy thinks
Three facts from the @sympy-tutorial "Gotchas" page that save hours. First, a SymPy symbol is not a Python variable: t = sp.symbols("t") makes a mathematical object named ; assigning to the Python name later does not change expressions already built. Second, == tests structural equality, not mathematical equality: (x+1)**2 == x**2 + 2*x + 1 is False; use sp.simplify(a - b) == 0 or sp.expand. Third, assumptions matter: declaring positive=True lets SymPy simplify to and pick the positive root of without a case split. Finally, lambdify((t, m, g, k), expr, modules="numpy") compiles an expression to a plain Python function that accepts NumPy arrays: that is the bridge from derivation to computation.
Every step of the hand derivation in 2.1โ2.5 has a one-line SymPy counterpart, and the code in part 3 is nothing more than this table written out:
| Derivation step | SymPy call | What to check |
|---|---|---|
| declare the quantities | sp.symbols("t v m g k", positive=True) |
assumptions match the physics () |
| write Newton's law | g - k*v**2/m |
units by hand (SymPy does not track them) |
| find from | sp.solve(sp.Eq(a, 0), v) |
exactly one positive root |
| verify a candidate | sp.simplify(sp.diff(vc, t) - a.subs(v, vc)) |
returns 0, and a wrong candidate does not |
| distance fallen | sp.integrate(v_expr, t) |
fix the constant so ; differentiate back |
| no-drag limit | sp.limit(v_expr, k, 0) |
equals g*t |
| small-time behaviour | sp.series(v_expr, t, 0, 4).removeO() |
leading term g*t, no term |
| sensitivity | sp.diff(a, v) |
matches a central difference |
| make it fast | sp.lambdify((t, m, g, k), v_expr, "numpy") |
hand values, limits, solve_ivp |
3. Build the computational model
Open starter/main.py. The symbols are declared once at the top so every function shares them.
Step 1: the equation of motion and terminal velocity
import sympy as sp
t, v, m, g, k = sp.symbols("t v m g k", positive=True)
def acceleration_expr():
return g - k * v**2 / m
def terminal_velocity_expr():
roots = sp.solve(sp.Eq(acceleration_expr(), 0), v)
(root,) = [r for r in roots if r.is_positive] # exactly one, thanks to positive=True
return root
Step 2: the exact solution, and the identity check
def velocity_expr():
vt = terminal_velocity_expr()
return vt * sp.tanh(g * t / vt)
def ode_residual(v_candidate):
return sp.simplify(sp.diff(v_candidate, t) - acceleration_expr().subs(v, v_candidate))
ode_residual(velocity_expr()) must return exactly 0. Try ode_residual(g*t) too: it returns , which is drag's missing term, and the test test_ode_residual_is_nonzero_for_a_wrong_candidate makes sure your residual function is not accidentally always zero. position_expr is ; the test differentiates it and compares with velocity_expr.
Step 3: limits and series
no_drag_limit is sp.limit(velocity_expr(), k, 0). small_time_series(order) is sp.series(velocity_expr(), t, 0, order).removeO(); the test reads off the , and coefficients with sp.Poly. acceleration_derivative_expr is sp.diff(acceleration_expr(), v).
Step 4: lambdify
def lambdify_velocity():
return sp.lambdify((t, m, g, k), velocity_expr(), modules="numpy")
Same pattern for acceleration, position and . Argument order is a contract: the tests call vel(ts, M, G, K).
Step 5: finite differences
central_difference(f, x, h) is three lines and must reject . derivative_check compares the lambdified with the central difference of the lambdified at speed . velocity_derivative_check compares with the central difference of at : this is the ODE verified numerically, which is what you would do if no closed form existed.
Verify
- Analytic case:
test_velocity_solves_the_ode_with_zero_initial_speed(residual exactly 0),test_position_is_the_integral_of_velocity. - Limiting cases: ; ; gives ; gives ; scaling of with and .
- Conservation-like property: the trapezoid integral of the lambdified reproduces the lambdified to m over 10 s; is monotone and bounded by .
- Convergence:
test_velocity_derivative_check_converges_at_second_orderrequires a rate above 1.8 as halves.
Compare
main() integrates the same ODE with scipy.integrate.solve_ivp (rtol=1e-10, atol=1e-12) and reports the maximum difference from the exact solution over 15 s: about m/s. The difference is the integrator's error, not the formula's: tighten the tolerances and it shrinks; loosen them to the defaults (rtol=1e-3) and it grows to m/s. The exact solution is the reference here; in Phase 03 the roles reverse and the integrator is tested on problems like this one precisely because the answer is known.
4. Experiment at home, or investigate real data
Mode: computational experiment. Map the error of the finite-difference derivative against the symbolic one.
- Fix the example parameters ( kg, m/sยฒ, kg/m) and s.
- For record
velocity_derivative_check(3.0, m, g, k, h)andderivative_check(20.0, m, g, k, h). - Before running, write down your prediction: at which is the first check smallest, and what slope do you expect on a log-log plot on each side of that minimum?
- Plot both errors against on log-log axes, add the lines and , and save as
fd_error_vs_h.png.
Raw data format: CSV with columns h, err_velocity_ode, err_dadv.
5. Validate and improve
Put the three error estimates side by side: the analytic truncation term , the rounding estimate , and the measurement. You should see the velocity check fall by a factor of 100 per decade from ( m/sยฒ) to (), reach a minimum near (), and then rise by a factor of 10 per decade: at and at . The slope +2 on the left is truncation; the slope โ1 on the right is rounding, because the subtraction loses leading digits as shrinks. The optimum sits near with m/s and m/sโด for this case, not at the textbook , which assumes . Explain that discrepancy in your note: the rule of thumb has hidden scale factors.
The acceleration check behaves differently: flat at to for every above , because a quadratic has no truncation term; only rounding is visible, and it too grows as shrinks. If you had seen a smooth decay there you would have to suspect your acceleration_expr is not quadratic.
Improvement: for the velocity check, use the five-point stencil and show the left slope becomes +4 while the right slope stays โ1, moving the optimum to a larger and a smaller minimum error.
6. Defend your work
Submit main.py, the test log, fall_with_drag.png, fd_error_vs_h.png with its CSV, and a one-page note (template in projects/_template/report-template.md) containing the derivation with assumptions, the three predictions for the package (, time to 99 % of , distance fallen by then) and the error-curve explanation.
Adversarial self-checks
- What if the mass doubles? rises by and the time constant with it; the distance fallen in the first second barely changes. Check all three with the lambdified functions.
- What if ? Drag vanishes quadratically, so the early motion is pure free fall; is there a speed below which quadratic drag is the wrong model (hint: Reynolds number below about 1)?
- Which assumption fails first in the real world? For a 1 km drop, none seriously; for a 30 km stratospheric drop, constant density: at 30 km is 1.5 % of sea level, so the early "terminal velocity" is eight times larger and the body decelerates as it descends. The symbolic solution no longer exists in closed form.
- What measurement could falsify the model? A video of the drop (P00.15) giving : a fit of with free should recover within the uncertainty of .
- Does the result survive a change of tool?
solve_ivpagrees to m/s;sp.dsolvereturns the same (extension). Which decision changes if is uncertain by ยฑ20 %? by โ10 %: the parachute opening altitude must carry that margin.
Check yourself
- Write the equation of motion for a falling body with quadratic drag and name the two assumptions that make a constant.
- Derive the units of and of .
- Why is
sp.simplify(a - b) == 0the right test of equality anda == bthe wrong one? - State the no-drag limit of and the long-time limit, and say which SymPy function finds each.
- The central difference of a quadratic is exact. Why, then, does
derivative_checknot return exactly zero? - For the example package, how long until the speed is within 1 % of terminal, and how far has it fallen by then? (Use .)
- What does
positive=Truebuy you when solving ? - On a log-log plot of finite-difference error against , what slopes do you expect on each side of the minimum, and which physical constant sets the right-hand side?
Problem set
Attempt every problem before opening solutions/. Record what you tried. State units on every numerical answer and say which results are exact (symbolic) and which are numerical.
Several problems use your personal seed s: the day of the month you were born (1โ31).
1. (Warm-up: the package)
An instrument package has mass kg, drag coefficient and frontal area mยฒ. Sea-level air, kg/mยณ, m/sยฒ.
Find: (a) the drag constant in kg/m; (b) the terminal velocity ; (c) the time constant ; (d) the time to reach 99 % of (use ); (e) the distance fallen by then. Check (b) with terminal_velocity_expr().subs(...) and (e) with lambdify_position(). Answer form: five numbers with units, four significant figures.
2. (Derivation: solve the equation of motion by hand)
Starting from with :
(a) Separate variables and integrate to obtain . Name each assumption where you use it (in particular where you need ).
(b) Integrate again to obtain with .
(c) Show that for , , and interpret the constant.
(d) Reproduce (a) in SymPy with sp.dsolve (extension) or by checking ode_residual, and (b) with sp.integrate. Report whether SymPy's form is identical to yours and, if not, how you proved them equal.
Answer form: derivation with steps named; one short paragraph for (c); SymPy transcript for (d).
3. (Unfamiliar scenario: thrown upward)
The same package (use kg, kg/m) is launched vertically upward at m/s. Take upward positive; drag now acts downward, and so does gravity.
(a) Write the equation of motion for the upward leg and explain why it is not the same equation as in the lesson with a sign change of .
(b) Solve it (by hand or with SymPy) to get and verify the result with an ode_residual-style check.
(c) Find the time to the apex and the apex height, both symbolically and numerically, and compare with the no-drag values and .
(d) Why does the lesson's velocity_expr not describe the fall after the apex if you simply shift the time origin? (It does; say why, in one sentence.)
Answer form: equation, derivation or SymPy transcript, four numbers with units, two sentences.
4. (Numerical, uses your code: the error curve)
Run the computational experiment of lesson part 4: velocity_derivative_check(3.0, 1.2, 9.80665, 0.006125, h) and derivative_check(20.0, ...) for .
(a) Tabulate and plot on log-log axes. Fit the slope on each side of the minimum for the velocity check. (b) Compute the predicted optimum at s using SymPy for , and compare with the measured minimum. (c) Implement the five-point stencil and repeat (a) for it. Report the new left-hand slope and the new minimum error.
Answer form: a table, two plots, two slopes with uncertainties, one paragraph.
5. (Series: when does drag matter?)
(a) From small_time_series(6) write down the relative deviation of from free fall, , to leading order in .
(b) Solve for the time at which that deviation reaches 1 % for the lesson's package, then evaluate the exact deviation at with lambdify_velocity and report the difference.
(c) A P00.15 experiment drops a ball from 2 m and times it to 0.01 s. Using as the yardstick, decide whether free fall is an adequate model for that experiment with a tennis ball ( g, mยฒ, ) and with a table-tennis ball ( g, mยฒ, ).
Answer form: one formula; one time and one percentage; two yes/no decisions each with a number.
6. (Judgment: where the model stops)
For each of the following, say which assumption of the lesson's model fails, estimate the size of the effect with one number, and say whether a symbolic closed form still exists:
(a) A 30 km stratospheric balloon drop (ISA density at 30 km is about 0.018 kg/mยณ). (b) The package tumbles, with varying between 0.006 and 0.014 mยฒ. (c) A 20 ยตm fog droplet falling in air (hint: compute the Reynolds number with Paยทs using the quadratic model's own ; at drag is linear in and Stokes' law gives ). Compare with a 2 mm raindrop. (d) The fall lasts long enough that changes by 0.1 % (how far is that?).
Answer form: four short paragraphs, each with a number.
7. (Hard, uses your code: linear versus quadratic drag)
A competing model uses linear drag, .
(a) Solve it symbolically for and find its terminal velocity and time constant. (b) Choose so that both models have the same as the lesson's package. Derive, for each model, the time to reach 90 % of in units of . Which model reaches terminal speed sooner, and why physically? (c) Lambdify both and plot them together with free fall for s. At s, which is faster and by how much? (d) Propose one measurement from a P00.15-style drop test that would tell the two models apart, and estimate the precision it needs.
Answer form: two formulas, two dimensionless times, a plot, one number with units, one paragraph.
Get the code
Clone the repository once, write your code in starter/main.py, then run the tests from the repository root.
pytest curriculum/phase-00/lesson-09-symbolic-math-sympy
To run the same tests against the reference solution instead:
AEFS_IMPL=solution pytest curriculum/phase-00/lesson-09-symbolic-math-sympy
Found a mistake? Every page is built from the Markdown in the repository; edit it on GitHub.