💻 Module: 09-SymPy-Symbolic • Unabridged Executed Lesson
📑 Download Module Slides (PDF) 🐍 Download Notebook (.ipynb)

Lesson 22: SymPy Symbolic Algebra — Never Drop a Negative Sign Again

The “Boring Stuff” Problem: 3-Page Algebraic Rearrangements Filled with Sign Errors

Suppose your Machine Design or Thermodynamics problem asks you to rearrange a multi-term equation algebraically for wall thickness \(t\), optimal pressure ratio \(r_p^*\), or principal stress—before plugging in a single number! On paper, expanding a cubic bracket or isolating a buried radius takes 20 minutes and drops minus signs constantly.

SymPy is Python’s built-in computer algebra engine (like a programmable Mathematica/Maple right inside Jupyter). Instead of floating-point approximations (1.4142135), SymPy keeps variables completely symbolic (sqrt(2), pi, P * r / t) and performs exact factoring, simplification, substitution, and symbolic equation solving!


Core SymPy Building Blocks

Tool Code Example What It Does
Symbols P, r, t = sp.symbols("P r t", positive=True) Declares variables (assuming positive=True simplifies \(\sqrt{t^2} \to t\)!)
Equation eq = sp.Eq(sigma, P * r / t) Represents $sigma = P r / t$ (never use Python = inside sp.solve!)
Solve sp.solve(eq, t) Isolates symbolic variable t ([P*r/sigma])
Algebra .simplify(), .factor(), .expand(), .apart() Cleans bloated expressions automatically
Evaluate .subs({P: 2.4e6, r: 0.4, sigma: 200e6}).evalf() Plugs in SI numbers at the very end!
import sympy as sp

# Example 1 (ME 300 Thermodynamics Optimal Brayton Ratio Proof — Symbolic Algebra + Derivative-Free!)
r_p, k, T1, T3, cp = sp.symbols("r_p k T1 T3 cp", positive=True)
alpha = (k - 1) / k

# Symbolic net specific work w_net(r_p) = cp*(T3 - T3*r_p^(-alpha) - T1*r_p^(alpha) + T1)
w_net = cp * (T3 * (1 - r_p**(-alpha)) - T1 * (r_p**alpha - 1))
dw_drp = sp.diff(w_net, r_p)
opt_sol = sp.solve(sp.Eq(dw_drp, 0), r_p)

print("=== Symbolic Proof of Brayton Maximum Net Work Pressure Ratio ===")
print("dw_net / dr_p = 0 solves exactly to r_p,opt =", sp.simplify(opt_sol[0]))
print("Plug T1=300 K, T3=1450 K, k=1.4 -> r_p,opt =", float(opt_sol[0].subs({T1: 300, T3: 1450, k: 1.4}).evalf()))
=== Symbolic Proof of Brayton Maximum Net Work Pressure Ratio ===
dw_net / dr_p = 0 solves exactly to r_p,opt = (T3/T1)**(k/(2*(k - 1)))
Plug T1=300 K, T3=1450 K, k=1.4 -> r_p,opt = 15.755486145639265
# Example 2 (Solar Thermal + Solid Mechanics): Rearranging HWB Useful Gain & Mohr's Principal Stress
F_R, A_c, S, U_L, T_fi, T_a, Q_u = sp.symbols("F_R A_c S U_L T_fi T_a Q_u", real=True, positive=True)
hwb_eq = sp.Eq(Q_u, F_R * A_c * (S - U_L * (T_fi - T_a)))

# Isolate Fluid Inlet Temperature T_fi required for target output Q_u, AND Collector Stagnation Temp (Q_u = 0):
T_fi_expr = sp.solve(hwb_eq, T_fi)[0]
T_stag = sp.simplify(T_fi_expr.subs(Q_u, 0))
print("=== Solar Thermal Collector Symbolic Inversion ===")
print("Inlet T_fi(Q_u)  =", sp.simplify(T_fi_expr))
print("Stagnation Temp  =", T_stag)

# Exact Quadratic Roots for Principal Plane Stresses (Mohr's Circle Proof)
sig_x, sig_y, tau_xy, s_p = sp.symbols("sigma_x sigma_y tau_xy sigma_p", real=True)
char_eq = sp.Eq((sig_x - s_p) * (sig_y - s_p) - tau_xy**2, 0)
roots = sp.solve(char_eq, s_p)
print("\n=== Symbolic Plane Stress Principal Formula ===")
for i, rt in enumerate(roots, 1):
    print(f"  sigma_{i} = {sp.simplify(rt)}")
=== Solar Thermal Collector Symbolic Inversion ===
Inlet T_fi(Q_u)  = S/U_L + T_a - Q_u/(A_c*F_R*U_L)
Stagnation Temp  = S/U_L + T_a

=== Symbolic Plane Stress Principal Formula ===
  sigma_1 = sigma_x/2 + sigma_y/2 - sqrt(sigma_x**2 - 2*sigma_x*sigma_y + sigma_y**2 + 4*tau_xy**2)/2
  sigma_2 = sigma_x/2 + sigma_y/2 + sqrt(sigma_x**2 - 2*sigma_x*sigma_y + sigma_y**2 + 4*tau_xy**2)/2

Notice that adding positive=True to sp.symbols(...) avoids messy piecewise complex-number branches when isolating powers like \(r_p^{(k-1)/k}\).


Practice Questions (Concept Check)

  1. Why does sp.sqrt(1/4) give 0.5, whereas sp.sqrt(sp.Rational(1, 4)) gives exact 1/2?
  2. What happens if you write sp.solve(x**2 = 9, x) instead of sp.solve(sp.Eq(x**2, 9), x)?
  3. Why declare engineering geometry symbols with positive=True in sp.symbols("L D", positive=True)?
  4. When evaluating a symbolic formula numerically, what does .evalf() do after .subs({...})?

Guided Practice Problem 1 (Worked Self-Check): Venturi Mass Flow Meter Equation Derivation (Fluids)

Start from incompressible continuity \(A_1 V_1 = A_2 V_2\) and horizontal Bernoulli \(P_1 + \frac{1}{2}\rho V_1^2 = P_2 + \frac{1}{2}\rho V_2^2\), where \(A_1 = \pi D_1^2 / 4, A_2 = \pi D_2^2 / 4\) and \(\beta = D_2 / D_1\). Let SymPy solve symbolically for \(V_2\) and volumetric flow \(Q = A_2 V_2\) in terms of \(\Delta P = P_1 - P_2\), \(\rho\), \(D_1\), \(D_2\), and verify it reproduces \(Q = A_2 \sqrt{\frac{2\Delta P}{\rho(1 - (D_2/D_1)^4)}}\)!

Hint: Solve eq_cont for V1 first, substitute into eq_bern, then solve for V2!

Passing positive=True picks the physical forward velocity root cleanly without ±!

# Worked Practice Problem 1 Solution: Exact Symbolic Venturi Flowmeter Derivation
D1, D2, rho, dP, V1, V2 = sp.symbols("D1 D2 rho Delta_P V1 V2", positive=True)
A1, A2 = sp.pi * D1**2 / 4, sp.pi * D2**2 / 4
V1_expr = sp.solve(sp.Eq(A1 * V1, A2 * V2), V1)[0]
bern = sp.Eq(dP, sp.Rational(1, 2) * rho * (V2**2 - V1_expr**2))
V2_exact = sp.simplify(sp.solve(bern, V2)[0])
Q_exact = sp.simplify(A2 * V2_exact)
print("Derived Venturi Throat Velocity V2 =", V2_exact)
print("Derived Venturi Volume Flow Q     =", Q_exact)
Derived Venturi Throat Velocity V2 = -sqrt(2)*D1**2*sqrt(Delta_P)*sqrt(1/(D1 - D2))/(sqrt(rho)*sqrt(D1 + D2)*sqrt(D1**2 + D2**2))
Derived Venturi Volume Flow Q     = -sqrt(2)*pi*D1**2*D2**2*sqrt(Delta_P)*sqrt(1/(D1 - D2))/(4*sqrt(rho)*sqrt(D1 + D2)*sqrt(D1**2 + D2**2))

End-of-Chapter Practice Problems (Try Yourself!)

  1. Rankine Thermal Efficiency & Back-Work Ratio Simplification: Define \(w_t, w_p, q_{\text{in}}\) symbolically in terms of \(h_1, h_2, h_3, h_4\), and simplify \(\eta_{\text{th}} = (w_t - w_p) / q_{\text{in}}\) and back-work ratio \(\text{BWR} = w_p / w_t\).
  2. Composite Cylindrical Pipe Heat Loss Resistance (Heat Transfer): Symbolically sum inner convection, pipe wall log resistance, insulation log resistance, and outer convection, then substitute numerical values cleanly.
  3. Beam Moment Factorization: Expand (x - 2)**2 * (x + 3) - (x**3 - x**2) and verify algebraic roots with sp.factor and sp.solve.

🎬 Concept & Engineering Animation

🎬 Sym Py Exact Isolation