Sub topic 16
Letting code solve the equations
This chapter assumes you can already draw a free-body diagram, choose axes, and write one component equation per axis and per object. It also assumes you can read basic Python and know what a matrix is. The aim is to stop doing the algebra by hand once the physics is written down. You still do the physics yourself. Code takes over the arithmetic.
What code does and does not do
Drawing the diagram and writing the equations is physics. Solving them is bookkeeping. For a single block that is easy to do by hand. With three connected objects, friction on two surfaces, and an unknown tension in each rope, the bookkeeping becomes the main source of mistakes.
Code helps in three ways:
- It solves simultaneous linear equations without algebra slips.
- It lets you change a number and rerun, so you can explore limiting cases quickly.
- With a symbolic library, it gives a formula you can check against intuition.
Code cannot catch a wrong free-body diagram. If you leave out a force or flip a sign in an equation, the program returns a confident wrong answer. The checks from the previous chapter still apply to every result.
From equations to a matrix
A set of linear equations in unknowns x can be written as A x = b. Each row of A holds the coefficients of one equation, and b holds the constants.
Take the Atwood machine with heavier mass m1 and lighter mass m2. Take down as positive for m1 and up as positive for m2, so both share the acceleration a. The two equations are:
- m1 g − T = m1 a, which rearranges to m1 a + T = m1 g
- T − m2 g = m2 a, which rearranges to −m2 a + T = m2 g
The unknowns are a and T. The code below builds the matrix and solves it:
import numpy as np
m1, m2 = 3.0, 2.0 # kg, m1 is the heavier hanging mass
g = 9.81 # m/s^2
# Unknown vector x = [a, T]
A = np.array([[ m1, 1.0],
[-m2, 1.0]])
b = np.array([m1 * g, m2 * g])
a, T = np.linalg.solve(A, b)
print(f"a = {a:.3f} m/s^2, T = {T:.3f} N")This prints a = 1.962 m/s^2, T = 23.544 N, the same result as the closed-form answer a = (m1 − m2) g / (m1 + m2).
Writing out the matrix form makes you list every unknown. If you have three unknowns and only two equations, solve raises an error. That error is useful: it tells you a relation is missing, such as a constraint that two objects share an acceleration.
Treating friction as an unknown
Friction is where code pays off. Instead of substituting by hand, add the friction force f as an unknown and write the friction law as its own row.
For a block sliding down an incline, with down-slope positive, use three unknowns: a, N, and f. The equations are:
- Perpendicular to the slope: N = m g cos θ
- Kinetic friction law: f − μk N = 0
- Along the slope: m a + f = m g sin θ
The function below also handles the question that comes first: does the block slide at all? On an incline, a block starting at rest stays put when tan θ ≤ μs, and the mass cancels from that test.
import math
import numpy as np
def block_on_incline(m, theta_deg, mu_s, mu_k, g=9.81):
theta = math.radians(theta_deg)
# Static case: no sliding, friction just balances the slope component.
if math.tan(theta) <= mu_s:
return {"state": "static",
"a": 0.0,
"N": m * g * math.cos(theta),
"f": m * g * math.sin(theta)}
# Sliding case: unknowns are [a, N, f].
A = np.array([[0.0, 1.0, 0.0], # N = m g cos(theta)
[0.0, -mu_k, 1.0], # f = mu_k N
[m, 0.0, 1.0]]) # m a + f = m g sin(theta)
b = np.array([m * g * math.cos(theta),
0.0,
m * g * math.sin(theta)])
a, N, f = np.linalg.solve(A, b)
return {"state": "sliding", "a": a, "N": N, "f": f}
for mu_s in (0.7, 0.3):
r = block_on_incline(m=5.0, theta_deg=30, mu_s=mu_s, mu_k=0.2)
print(f"mu_s={mu_s}: {r['state']}, a={r['a']:.2f} m/s^2, "
f"N={r['N']:.2f} N, f={r['f']:.2f} N")With μs = 0.7, tan 30° ≈ 0.577 is below the limit, so the block stays at rest and a is zero. With μs = 0.3, the block slides. The output is N = 42.48 N, f = 8.50 N, and a = 3.21 m/s², which matches the hand calculation.
Getting a formula with SymPy
A numeric answer tells you one case. A symbolic answer tells you the structure, and that lets you test limits. SymPy is a Python library for symbolic algebra. Here it solves the Atwood equations with letters instead of numbers:
import sympy as sp
m1, m2, g = sp.symbols("m1 m2 g", positive=True)
a, T = sp.symbols("a T")
equations = [sp.Eq(m1 * g - T, m1 * a),
sp.Eq(T - m2 * g, m2 * a)]
sol = sp.solve(equations, [a, T], dict=True)[0]
print("a =", sp.simplify(sol[a]))
print("T =", sp.simplify(sol[T]))
# Limiting cases
print("m1 = m2 ->", sp.simplify(sol[a].subs(m1, m2)))
print("m2 -> 0 ->", sp.limit(sol[a], m2, 0))The result is equivalent to a = g (m1 − m2) / (m1 + m2) and T = 2 g m1 m2 / (m1 + m2). The two limit checks print 0 and g:
- With equal masses, a is zero. The system balances.
- With m2 near zero, a approaches g. The heavy mass is in free fall.
Both match physical intuition. This is the "limiting cases" check from the previous chapter, done by the computer.
Choosing between numeric and symbolic
| Situation | Better tool | Reason |
|---|---|---|
| One problem with given numbers | NumPy `solve` | Fast, and the matrix shows every unknown |
| You want to know how the answer depends on a parameter | SymPy | The formula exposes the dependence |
| Sweeping an angle or coefficient over many values | NumPy in a loop | Cheap to rerun, easy to plot |
| Equations contain a mix of branches (static or kinetic) | Plain Python `if` plus either solver | The branch is a physics decision |
Common errors
- Inconsistent sign conventions. If m1 moves down and m2 moves up, the shared acceleration is positive for m1's down direction and for m2's up direction. Write the convention in a comment next to the matrix.
- Missing equation.
np.linalg.solveraisesLinAlgErrorwhen the matrix is singular. This usually means you have fewer independent equations than unknowns, or two rows say the same thing. - Hidden friction direction. The friction law f = μk N gives only the magnitude. Check that the direction in your along-slope equation opposes the motion. If the object could slide either way, test both cases.
- Degrees versus radians.
math.sinandmath.cosexpect radians. Convert withmath.radians. - Trusting a negative tension or normal force. A negative N or T means the rope has gone slack or the surface has lost contact. The model has broken, so rethink the setup.
Exercise
A block of mass m sits on a rough horizontal table and is connected by a light rope over a frictionless pulley to a hanging mass M. The table has kinetic friction coefficient μk. Assuming the block slides toward the pulley, list the unknowns and write the three rows of A and b for NumPy. Use the unknown order [a, T, N].
Show answer
Unknowns are a, T, and N. Taking motion toward the pulley and downward for M as positive, the equations are: Table block, vertical: N = m g. Table block, horizontal: T − μk N = m a. Hanging mass: M g − T = M a. In matrix form with x = [a, T, N]: row 1 is [0, 0, 1] with b = m g; row 2 is [−m, 1, −μk] with b = 0; row 3 is [M, 1, 0] with b = M g. Solving gives a = (M − μk m) g / (M + m). If M < μk m, this is negative, which means the block does not slide and the static case applies, so the kinetic model is invalid there.