Chapter 3: The Numerical Engine - State Space and Time Integration
Every chapter so far has leaned on one magic line, sd.sdof_response(...), with
the promise that you would build it yourself, and this chapter keeps that
promise. By the end you will have written, from scratch, the solver that the rest
of the book quietly calls for harmonic loads, blast pulses, wind, and
earthquakes. There is no new physics here, only one equation,
(1), and three honest ways to march it forward in time.
The strategy is the spine of the whole book: cast the equation of motion into state space, a first-order form that general-purpose solvers integrate natively, and then step it. We will meet the exact stepper first, a matrix exponential that is correct to machine precision. Then come the two approximate steppers every structural-dynamics code actually ships with, Newmark- and the central-difference method, and the chapter ends by watching how their error shrinks as you refine the time step.
1Why computers want first-order equations¶
Figure 1 maps the route this chapter takes from the equation of motion to a working solver. The top row is a change of variables: stacking the displacement and the velocity into one state vector turns the second-order equation of motion into a first-order system. The bottom row is the march: once that system is discretized over a step , two constant matrices carry the state from one instant to the next, and a loop repeats that single operation until the record ends. The first two sections below derive the two rows in turn.
Figure 1:The plan of the chapter: the second-order equation of motion recast as a first-order state-space system (top), and the discretized one-step march that a loop repeats (bottom).
General-purpose ODE solvers, such as SciPy’s solve_ivp or MATLAB’s ode45,
cannot take (1) as written, because it is second order: the
highest derivative is . They are built to advance a first-order system
one that says “given the state right now, here is its rate of change.” The trick, borrowed from control theory, is to stack the displacement and the velocity into a single state vector so that the one second-order equation becomes two coupled first-order equations. Structural codes such as OpenSees take the other route and integrate the second-order form directly with Newmark’s method, which this chapter meets later; the first-order form is the one that admits an exact step.
Define the state
the displacement on top and the velocity underneath, so its time derivative is . The top row is free: is literally the second entry of . The bottom row comes straight from (1), solved for the acceleration:
Write those two rows as a matrix-vector product and the second-order equation has become a clean first-order state-space system:
That is the entire recast: read off the top and bottom rows of (5) and you recover and (4). The matrix holds the structure (its mass, damping, and stiffness); the vector says where the load enters (it pushes the velocity, never the position directly), and together they make up the top row of Figure 1.
In code, and are four numbers and two numbers. The engine exposes them as
sd.state_space, and we can confirm they match (5) by hand. We use
the same idealized one-story frame as Chapter 1
throughout, so the numbers stay familiar.
# The idealized one-story steel frame. SI units: tonnes, kN, m, s.
m = 2.0 # roof mass (t)
k = 50.0 # lateral stiffness (kN/m)
zeta = 0.05 # damping ratio (5%)
c = 2 * zeta * np.sqrt(k * m) # damping coefficient (kN*s/m)
A, B = sd.state_space(m, c, k)
print("A =\n", A)
print("B =\n", B.ravel())
props = sd.natural(m, c, k)
print(f"\nTn = {props['Tn']:.3f} s, wn = {props['wn']:.3f} rad/s, zeta = {props['zeta']:.3f}")A =
[[ 0. 1. ]
[-25. -0.5]]
B =
[0. 0.5]
Tn = 1.257 s, wn = 5.000 rad/s, zeta = 0.050
The bottom-left entry is and the bottom-right is , while injects into the velocity equation. There is nothing mysterious in either matrix: they are the equation of motion, rearranged so a computer can read it.
2The exact step: a matrix exponential¶
To see why a clean solution exists, forget matrices for a moment and look at the scalar version of (5). The simplest first-order equation is
a single number in place of the matrix . Every calculus course shows its solution: the function whose rate of change is proportional to itself is the exponential, so starting from :
Step forward by and the multiplier that carries to is just the number . The state-space equation (take for the moment) is exactly this same equation, only with a matrix instead of the scalar and a vector instead of . It would be remarkable if the answer were different, and it is not. The solution is
where is the matrix exponential: the matrix analogue of , defined by feeding the matrix into the very same power series that defines the scalar exponential:
Differentiate that series term by term and you get , so genuinely satisfies , exactly as in the scalar case. The matrix is the propagator: hand it any state and it returns that state advanced by a time , with no approximation.
Figure 2 shows what that means in the phase plane of Chapter 2, for a lightly damped oscillator in free vibration. Each dot is the state one step of after the last, obtained by multiplying by , and every dot sits exactly on the continuous spiral, however coarse the step. Keeping only the first two terms of the series (9), , moves the state along the tangent instead, and that single step already lands off the curve.
Figure 2:Free vibration in the phase plane: exact steps (dots) on the continuous trajectory, and a single tangent step (square).
Now restore the load, held constant across each step: for , the zero-order hold (ZOH) assumption. Then is the same linear equation with a constant push, and integrating it over the step (homogeneous propagator plus the particular response to the constant ) gives the exact one-step march
The first term propagates the current state forward by ; the second, , is what the constant force adds over the step (it is written in closed form). The two discrete operators and are computed once and do not change from step to step, because , , , and are constant, and then (10) is just a matrix multiply per step. That is the loop on the bottom row of Figure 1.
The whole solver fits in about a dozen lines. Let us write it plainly, without
reaching for sdtools, so you can see there is no sleight of hand.
from scipy.linalg import expm, solve
def exact_step(m, c, k, p, dt, u0=0.0, v0=0.0):
"""Exact (matrix-exponential, zero-order-hold) SDOF solver."""
A, B = sd.state_space(m, c, k)
Ad = expm(A * dt) # e^{A dt}, computed once
Bd = solve(A, (Ad - np.eye(2)) @ B) # A^{-1}(Ad - I) B, exact for ZOH
N = p.size
z = np.array([u0, v0], float)
u = np.empty(N); v = np.empty(N)
u[0], v[0] = u0, v0
for i in range(N - 1): # the one-step march
z = Ad @ z + Bd[:, 0] * p[i]
u[i + 1], v[i + 1] = z
a = (p - c * v - k * u) / m # acceleration from the EOM
return np.arange(N) * dt, u, v, a2.1Verifying against the truth¶
Chapter 2 gives us a closed-form answer to check against. For free vibration () of an underdamped oscillator released from with velocity , the displacement is
with . Let us nudge the roof by 20 mm, release it, and compare our hand-written solver to this exact formula.
dt = 0.01
t = np.arange(0, 6.0, dt)
u0, v0 = 0.020, 0.0 # 20 mm initial nudge, released
# numerical (matrix exponential) solution
t, u_num, _, _ = exact_step(m, c, k, np.zeros(t.size), dt, u0=u0, v0=v0)
# analytic free-vibration solution from Chapter 2
wn, wd = props["wn"], props["wd"]
zw = props["zeta"] * wn
u_exact = np.exp(-zw * t) * (u0*np.cos(wd*t) + (v0 + zw*u0)/wd*np.sin(wd*t))
print(f"maximum absolute error over 6 s : {np.max(np.abs(u_num - u_exact)):.2e} m")maximum absolute error over 6 s : 4.42e-17 m
fig, ax = plt.subplots(figsize=(7.4, 3.0))
ax.plot(t, u_exact * 1000, color=sd.PLT[0], lw=2.4, label="analytic (Ch. 2)")
ax.plot(t[::8], u_num[::8] * 1000, "o", color=sd.PLT[1], ms=5,
mfc="white", mew=1.6, label="matrix exponential")
ax.axhline(0, color="#9aa3ab", lw=1.0)
ax.set_xlabel(r"time $t$ (s)")
ax.set_ylabel(r"roof drift $u$ (mm)")
ax.legend(loc="upper right")
plt.show()

Figure 3:The matrix-exponential solver (markers) laid on top of the exact damped free-vibration formula (line).
The error is m, machine precision, and that is worth pausing on. The matrix exponential does not approximate the free-vibration response; it reproduces (11) term for term, because is the exact propagator of a linear system. The only approximation in (10) is the zero-order hold on the forcing, and when there is no forcing there is nothing left to approximate.
_, u_sd, _, _ = sd.sdof_response(m, c, k, np.zeros(t.size), dt, u0=u0, v0=v0, method="exp")
print(f"our exact_step vs sd.sdof_response -> max difference = {np.max(np.abs(u_num - u_sd)):.2e}")our exact_step vs sd.sdof_response -> max difference = 0.00e+00
The difference is exactly zero, so there is no hidden machinery. When Chapter 6 builds a response spectrum by solving hundreds of oscillators, this is the loop running inside.
3Newmark-: the structural-dynamics workhorse¶
If the matrix exponential is exact, why does any engineering code bother with anything else? The first reason is that is exact only for a linear, time-invariant system: the moment the structure yields (steel that goes plastic, a gap that closes), changes every step and the clean propagator is gone. The second is that the profession standardized decades ago on a family of steppers that work directly with , , and extend gracefully to nonlinear problems. The most popular is Newmark- (Newmark, 1959).
Newmark’s idea is to assume a shape for how the acceleration varies across one step, then integrate that shape once to get the velocity and twice to get the displacement. Figure 4 shows the two shapes in common use. Inside one step the true acceleration (dashed) is unknown, but its two end values are tied to the equation of motion at the start and the end of the step. The average-acceleration rule replaces it with the constant mean of the two ends and the linear-acceleration rule with a straight line between them, and in both cases the shaded area under the assumed shape is the change in velocity across the step.
Figure 4:The acceleration assumed inside one time step by the average-acceleration rule (left) and the linear-acceleration rule (right), against an unknown true variation through the same end values.
The simplest useful assumption is the left one: the acceleration is constant over the step, equal to the average of its two endpoints:
Integrating this constant from (where the velocity is and the displacement is ) gives, at :
Substitute back in and these are exactly the two update formulas Newmark uses. Newmark wrote them with two tunable weights and so that other acceleration shapes (linear, for instance) fit the same template:
Setting and collapses
(14) straight back to the average-acceleration integral
(13). To check, note that the velocity bracket becomes
, and the displacement bracket becomes
as well. This average-acceleration
rule (also called the trapezoidal rule) is special: it is unconditionally stable,
meaning it never blows up no matter how large the time step, and it conserves
energy exactly for an undamped oscillator. It is the default in OpenSees and the
default behind sd.newmark. The linear-acceleration rule on the right of
Figure 4 is the case ,
, which is more accurate per step but stable only for
.
To turn (14) into a usable stepper, substitute them into the equation of motion written at step and solve for . For our linear SDOF that solve is a single division by an effective stiffness , after which the velocity and acceleration follow.
Example 1 takes one pass through Algorithm 2 by hand, so that every quantity in the loop has a number attached to it.
Here is the implementation, following the algorithm line for line.
def newmark_step(m, c, k, p, dt, u0=0.0, v0=0.0, gamma=0.5, beta=0.25):
"""Newmark-beta SDOF solver (default = average acceleration)."""
N = p.size
u = np.empty(N); v = np.empty(N); a = np.empty(N)
u[0], v[0] = u0, v0
a[0] = (p[0] - c*v0 - k*u0) / m
a1 = m/(beta*dt**2) + c*gamma/(beta*dt)
a2 = m/(beta*dt) + c*(gamma/beta - 1.0)
a3 = m*(1/(2*beta) - 1.0) + c*dt*(gamma/(2*beta) - 1.0)
k_hat = k + a1
for i in range(N - 1):
p_hat = p[i+1] + a1*u[i] + a2*v[i] + a3*a[i]
u[i+1] = p_hat / k_hat
v[i+1] = gamma/(beta*dt)*(u[i+1]-u[i]) + (1-gamma/beta)*v[i] \
+ dt*(1 - gamma/(2*beta))*a[i]
a[i+1] = 1/(beta*dt**2)*(u[i+1]-u[i]) - 1/(beta*dt)*v[i] \
- (1/(2*beta) - 1)*a[i]
return np.arange(N)*dt, u, v, aThe next cell runs that function for a single step and repeats Example 1, including the equilibrium check and the exact value.
# One step by hand (ex-ch03-newmark-step): free vibration from 20 mm, dt = 0.1 s.
dt1, gamma, beta = 0.1, 0.5, 0.25
a1 = m/(beta*dt1**2) + c*gamma/(beta*dt1)
a2 = m/(beta*dt1) + c*(gamma/beta - 1.0)
a3 = m*(1/(2*beta) - 1.0) + c*dt1*(gamma/(2*beta) - 1.0)
print(f"a1 = {a1:.0f} a2 = {a2:.0f} a3 = {a3:.0f} k_hat = {k + a1:.0f}")
_, u1s, v1s, acc1s = newmark_step(m, c, k, np.zeros(2), dt1, u0=0.020)
print(f"step 1: u = {u1s[1]:.5f} m v = {v1s[1]:.4f} m/s a = {acc1s[1]:.4f} m/s^2")
print(f"equilibrium check m*a + c*v + k*u = {m*acc1s[1] + c*v1s[1] + k*u1s[1]:.1e} kN")
_, u1e, _, _ = exact_step(m, c, k, np.zeros(2), dt1, u0=0.020)
print(f"exact at t = 0.1 s: u = {1000*u1e[1]:.2f} mm (Newmark {1000*u1s[1]:.2f} mm, "
f"{100*(u1s[1]/u1e[1] - 1):.1f}% high)")a1 = 820 a2 = 81 a3 = 2 k_hat = 870
step 1: u = 0.01770 m v = -0.0460 m/s a = -0.4195 m/s^2
equilibrium check m*a + c*v + k*u = 3.3e-16 kN
exact at t = 0.1 s: u = 17.59 mm (Newmark 17.70 mm, 0.6% high)
Cross-check the function three ways: against the library’s sd.newmark, against
the exact matrix-exponential solver, and, for good measure, under a genuine
forced load, not just free vibration. We drive the frame with a short
sinusoidal push.
dt = 0.01
t = np.arange(0, 6.0, dt)
# free vibration: Newmark vs exact
_, uN, _, _ = newmark_step(m, c, k, np.zeros(t.size), dt, u0=u0, v0=v0)
_, uE, _, _ = exact_step (m, c, k, np.zeros(t.size), dt, u0=u0, v0=v0)
print(f"free vibration : Newmark vs exact, peak diff = {np.max(np.abs(uN-uE)):.2e} m")
print(f"our newmark_step vs sd.newmark = {np.max(np.abs(uN - sd.newmark(m,c,k,np.zeros(t.size),dt,u0=u0,v0=v0)[1])):.2e} m")
# forced: a 2 s sinusoidal push at 1 Hz, then release
p = 10.0 * np.sin(2*np.pi*1.0*t) * (t < 2.0)
_, uNf, _, _ = newmark_step(m, c, k, p, dt)
_, uEf, _, _ = exact_step (m, c, k, p, dt)
print(f"forced (pulse) : peak |u| Newmark = {1000*np.max(np.abs(uNf)):.3f} mm, "
f"exact = {1000*np.max(np.abs(uEf)):.3f} mm")free vibration : Newmark vs exact, peak diff = 3.07e-05 m
our newmark_step vs sd.newmark = 0.00e+00 m
forced (pulse) : peak |u| Newmark = 619.101 mm, exact = 619.523 mm
The two solvers agree to well under a percent at this step size: the
free-vibration traces differ by at most 0.031 mm on a 20 mm swing, and the
forced peaks by 0.07 %. The small residual is exactly the approximation Newmark
makes and the matrix exponential does not, and it shrinks predictably as
falls, which we quantify in
the convergence section. The same sd engine reaches
Newmark through sd.sdof_response(..., method="newmark"); it is the path
Chapter 7 follows when the spring stops being linear.
4Central difference: cheap, explicit, and only sometimes stable¶
The third stepper is the simplest of all. The central-difference method approximates the velocity and acceleration at step with symmetric finite differences of the displacement:
substitutes them into the equation of motion at step , and solves for the one
unknown . Because the equation is written at step (where everything
except is already known), no system solve is needed at all: the method
is explicit. That makes each step extraordinarily cheap, which is why
explicit integration dominates impact, blast, and crash simulation. The engine
provides it as sd.central_difference.
Figure 5 pictures both the stencil and its price. Three displacement samples one step apart fix a parabola (left): the slope of the dashed chord through the outer two estimates the velocity at the middle point, and the change between the two green half-step slopes estimates the acceleration. The right panel plots the amplification factor , the factor by which one step multiplies the amplitude of undamped free vibration. Average-acceleration Newmark keeps for any step, while central difference does so only up to and then jumps above one, which the derivation below explains.
Figure 5:The central-difference stencil on a displacement history (left) and the amplification factor of one step for undamped free vibration, central difference against average-acceleration Newmark (right).
def central_step(m, c, k, p, dt, u0=0.0, v0=0.0):
"""Explicit central-difference SDOF solver (conditionally stable)."""
N = p.size
u = np.empty(N); u[0] = u0
a0 = (p[0] - c*v0 - k*u0) / m
u_m1 = u0 - dt*v0 + 0.5*dt**2*a0 # fictitious u at t = -dt
k_hat = m/dt**2 + c/(2*dt)
A_ = m/dt**2 - c/(2*dt)
B_ = k - 2*m/dt**2
u_prev = u_m1
for i in range(N - 1):
u[i+1] = (p[i] - A_*u_prev - B_*u[i]) / k_hat
u_prev = u[i]
v = np.gradient(u, dt)
a = (p - c*v - k*u) / m
return np.arange(N)*dt, u, v, aBut the cheapness comes with a string attached. The central-difference method is only conditionally stable: the time step must be smaller than a critical value set by the natural period:
That is not arbitrary; it falls out of asking when one step amplifies the last. Apply the scheme to undamped free vibration (, ): substituting the two finite differences (17) into and using gives the three-term recurrence
A recurrence like this has solutions of the form , and the motion stays bounded only if . Plugging into the recurrence gives the characteristic quadratic . Its two roots multiply to 1, so they sit as a distinct conjugate pair on the unit circle (the bounded, oscillatory case) only while the middle coefficient stays strictly within . At the endpoint the two roots coincide at , and a repeated root on the circle grows linearly (), already unstable; push any further below -2 and one root jumps outside the unit circle, , so every step magnifies the previous one. The threshold is therefore , i.e. , and since :
Step past that limit and the algorithm does not merely lose accuracy: it explodes, each step amplifying the last, exactly as the root predicts. Our frame has s, so s, and the next two cells watch the explosion happen on either side of that limit.
dt_cr = props["Tn"] / np.pi
print(f"Tn = {props['Tn']:.3f} s -> stability limit dt_cr = Tn/pi = {dt_cr:.3f} s")
def cd_free(dt, T_end=8.0):
t = np.arange(0, T_end, dt)
t, u, _, _ = central_step(m, c, k, np.zeros(t.size), dt, u0=u0, v0=v0)
return t, u
t_ok, u_ok = cd_free(0.05) # well below the limit -> stable
t_bad, u_bad = cd_free(0.42) # just above the limit -> blows up
print(f"dt = 0.05 s (< dt_cr): peak |u| = {1000*np.max(np.abs(u_ok)):8.2f} mm (well behaved)")
print(f"dt = 0.42 s (> dt_cr): peak |u| = {np.max(np.abs(u_bad)):8.2e} m (diverged)")Tn = 1.257 s -> stability limit dt_cr = Tn/pi = 0.400 s
dt = 0.05 s (< dt_cr): peak |u| = 20.00 mm (well behaved)
dt = 0.42 s (> dt_cr): peak |u| = 3.04e+02 m (diverged)
fig, (axL, axR) = plt.subplots(1, 2, figsize=(8.6, 3.1))
axL.plot(t_ok, u_ok * 1000, color=sd.PLT[2])
axL.axhline(0, color="#9aa3ab", lw=1.0)
axL.set_title(r"$\Delta t = 0.05$ s $(<\Delta t_\mathrm{cr})$", fontsize=12)
axL.set_xlabel(r"time $t$ (s)"); axL.set_ylabel(r"$u$ (mm)")
axR.semilogy(t_bad, np.abs(u_bad), color=sd.PLT[1])
axR.set_title(r"$\Delta t = 0.42$ s $(>\Delta t_\mathrm{cr})$", fontsize=12)
axR.set_xlabel(r"time $t$ (s)"); axR.set_ylabel(r"$|u|$ (m, log scale)")
fig.tight_layout()
plt.show()

Figure 6:Central-difference free vibration of the frame with s, below (left, linear axis), and with s, just above it (right, logarithmic axis).
With s the response decays exactly as it should. With s, a hair above the limit, it climbs from 20 mm to 304 m in eight seconds, more than four orders of magnitude, although the structure itself is perfectly well behaved: the blow-up is a property of the algorithm. Two lessons hide in Figure 6, and the first is practical: an explicit code must police its time step against (18), and for a real multi-story building the relevant is the shortest (highest-mode) period, which can be tiny, forcing a very small . The second is reassuring: the matrix exponential and average-acceleration Newmark have no such limit. They are unconditionally stable; you choose for accuracy, never to avoid catastrophe.
▶ Interactive: growing the time step past
Three copies of the frame are released from 20 mm. The first follows the exact solution, the second is integrated with average-acceleration Newmark (blue), and the third with central difference (orange); the two numerical frames move only when their integrator completes a step. The slider sets the time step from to , and the buttons jump to the steps discussed below. In the plot the markers are the computed steps, drawn against the exact decay (gray); a value beyond the mm scale is marked by an arrow with its magnitude. The note reports the step, the stability limit , and whether each run stayed bounded.
Below the limit both methods stay bounded, and their dots drift off the exact curve as the step grows, Newmark falling behind and central difference running ahead. One notch past the central-difference run starts to grow, reaching 0.17 m by 8 s at and 15,345 m at , while Newmark stays bounded even with fewer than three steps per period.
5Accuracy and stability versus the time step¶
With three working solvers in hand, the next questions are how wrong each one is and how fast it improves as you shrink . Because we have an exact answer for free vibration, (11), we can measure the error honestly. For each step size we run all three methods, compare to the analytic trace, and report the root-mean-square error normalized by the peak amplitude.
def rms_error(method, dt, T_end=6.0):
"""Normalized RMS error of a free-vibration run against the exact formula."""
t = np.arange(0, T_end, dt)
p = np.zeros(t.size)
if method == "exp": _, u, _, _ = exact_step (m, c, k, p, dt, u0=u0, v0=v0)
elif method == "newmark": _, u, _, _ = newmark_step(m, c, k, p, dt, u0=u0, v0=v0)
else: _, u, _, _ = central_step(m, c, k, p, dt, u0=u0, v0=v0)
ua = np.exp(-zw*t) * (u0*np.cos(wd*t) + (v0 + zw*u0)/wd*np.sin(wd*t))
return np.sqrt(np.mean((u - ua)**2)) / np.max(np.abs(ua))
dts = np.logspace(np.log10(0.004), np.log10(0.16), 14)
err = {mth: np.array([rms_error(mth, d) for d in dts])
for mth in ("exp", "newmark", "central")}
for mth in ("exp", "newmark", "central"):
print(f"{mth:8s}: error at dt=0.004 -> {err[mth][0]:.2e}, at dt=0.16 -> {err[mth][-1]:.2e}")exp : error at dt=0.004 -> 5.88e-15, at dt=0.16 -> 1.60e-15
newmark : error at dt=0.004 -> 1.47e-04, at dt=0.16 -> 2.16e-01
central : error at dt=0.004 -> 7.64e-05, at dt=0.16 -> 1.30e-01
fig, ax = plt.subplots(figsize=(6.6, 4.2))
ax.loglog(dts, err["central"], "s-", color=sd.PLT[1], label="central difference")
ax.loglog(dts, err["newmark"], "o-", color=sd.PLT[0], label="Newmark (avg. accel.)")
ax.loglog(dts, np.maximum(err["exp"], 1e-16), "^-", color=sd.PLT[2],
label="matrix exponential")
# slope-2 reference guide
g = 0.5 * err["central"][-1] * (dts / dts[-1])**2
ax.loglog(dts, g, "--", color="#9aa3ab", lw=1.6)
ax.text(dts[7], g[7] / 4.5, "slope 2", color="#6b7280", fontsize=11.5, ha="center", va="center",
bbox=dict(facecolor="white", edgecolor="none", pad=1.0))
ax.set_xlabel(r"time step $\Delta t$ (s)")
ax.set_ylabel("normalized RMS error")
ax.legend(loc="center left", framealpha=0.9)
plt.show()

Figure 7:Convergence of the three integrators on the free-vibration test: normalized RMS error versus time step on log-log axes, with a slope-2 reference guide.
The log-log slopes of Figure 7 tell the whole story. Newmark and central difference are both second-order methods: their error scales as , so the curves are straight lines of slope 2 and halving the step cuts the error by four. The matrix exponential, by contrast, lies pinned at round-off for every step, a flat line at , confirming once more that for a linear system it is not approximating anything.
5.1What Newmark gets wrong: period elongation¶
Second-order accuracy describes how the error shrinks; it does not describe its character. The average-acceleration Newmark rule has a famous, well-understood fingerprint: it elongates the period slightly (the numerical oscillation runs a touch slow) while keeping the amplitude essentially right. The central- difference method does the opposite, shortening the period. We can see both by running a deliberately coarse step and overlaying the exact answer.
dt = 0.10
t = np.arange(0, 4.0, dt)
p = np.zeros(t.size)
_, uN, _, _ = newmark_step(m, c, k, p, dt, u0=u0, v0=v0)
_, uC, _, _ = central_step(m, c, k, p, dt, u0=u0, v0=v0)
t_fine = np.arange(0, 4.0, 0.002)
u_fine = np.exp(-zw*t_fine)*(u0*np.cos(wd*t_fine) + (v0+zw*u0)/wd*np.sin(wd*t_fine))
fig, ax = plt.subplots(figsize=(7.6, 3.1))
ax.plot(t_fine, u_fine*1000, color="#9aa3ab", lw=2.0, label="exact")
ax.plot(t, uN*1000, "o-", color=sd.PLT[0], ms=4, lw=1.6, label="Newmark (lags)")
ax.plot(t, uC*1000, "s-", color=sd.PLT[1], ms=4, lw=1.6, label="central diff. (leads)")
ax.axhline(0, color="#cfd5da", lw=0.8)
ax.set_xlabel(r"time $t$ (s)")
ax.set_ylabel(r"roof drift $u$ (mm)")
ax.legend(loc="upper right", ncol=1)
plt.show()

Figure 8:Period distortion at a coarse step ( s, about ): against the exact trace (gray), Newmark’s average-acceleration rule lags while central difference leads, both keeping the amplitude faithful.
# Quantify the period drift directly from the downward zero-crossings.
def mean_period(t, u):
s = np.sign(u)
zc = np.where(np.diff(s) < 0)[0] # downward crossings
tc = t[zc] - u[zc]*(t[zc+1]-t[zc])/(u[zc+1]-u[zc])
return np.mean(np.diff(tc))
Td = 2*np.pi / wd
print(f"exact damped period Td = {Td:.4f} s")
print(f"Newmark period (dt=0.10) = {mean_period(t, uN):.4f} s "
f"(+{100*(mean_period(t,uN)/Td - 1):.1f}% elongated)")
print(f"central period (dt=0.10) = {mean_period(t, uC):.4f} s "
f"({100*(mean_period(t,uC)/Td - 1):+.1f}% shortened)")
# The same check at the common rule-of-thumb step dt = Tn/20.
dt20 = props["Tn"] / 20
t20 = np.arange(0, 8.0, dt20)
_, uN20, _, _ = newmark_step(m, c, k, np.zeros(t20.size), dt20, u0=u0, v0=v0)
print(f"Newmark period (dt=Tn/20) = {mean_period(t20, uN20):.4f} s "
f"(+{100*(mean_period(t20, uN20)/Td - 1):.1f}% elongated)")exact damped period Td = 1.2582 s
Newmark period (dt=0.10) = 1.2833 s (+2.0% elongated)
central period (dt=0.10) = 1.2446 s (-1.1% shortened)
Newmark period (dt=Tn/20) = 1.2684 s (+0.8% elongated)
A 2 % period error sounds harmless, but over a long earthquake record it accumulates into a visible phase shift, and near a resonance peak a small frequency error can move the response noticeably. The cure is simply a finer step, or the matrix exponential when the system is linear. A common rule of thumb is for the mode you care about, and at that step the Newmark period error printed above falls to 0.8 %. Knowing the character of each method’s error is what lets you pick the step with confidence instead of superstition.
6The engine, demystified¶
We set out to build the solver the rest of the book takes for granted, and three ideas did all the work:
State space. Stacking turns the one second-order equation of motion (1) into the first-order system (5) that general-purpose solvers integrate natively (Figure 1).
The exact step. With a zero-order hold on the load, one step is the matrix exponential, (10), exact to machine precision for any linear system, and unconditionally stable. This is precisely
sd.sdof_response(..., method="exp").The practical steppers. Average-acceleration Newmark (unconditionally stable, second order, mild period elongation) is the workhorse that survives into nonlinear analysis in Chapter 7; the explicit central-difference method is cheaper still but only conditionally stable, .
From here on, “solve the SDOF” is a settled, one-line operation. The next three
chapters (harmonic and periodic loads in Chapter 4,
arbitrary and measured loads in Chapter 5, and
earthquake response spectra in Chapter 6) do nothing
more than hand a different to sd.sdof_response and plot what comes back.
You now know exactly what happens inside that call. The full sdtools API, every
function the later chapters lean on, is cataloged in
Appendix B.