Phase 10 / Scientific computing
A functional physical simulation
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 85 minutes · CPU practice
Implement a pure scalar state transition with units and a fixed time grid. Separate a discrete implementation oracle from continuous approximation error.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Math & optimization
Hardware: CPU
Setup help: Python, notebook, or Cloud TPU VM
Use the tested CPU packages (the recorded environment uses Python 3.14.3). Other Python versions require separate checks. Hardware receipts apply only to their recorded source, environment, hardware, and cases; they do not qualify every lesson or TPU configuration. See the TPU performance and hardware evidence guide. The optional Cloud TPU specialization explains target-specific execution boundaries. Logical CPU devices practice partitioning; they do not simulate TPU performance.
Download the repository ZIP or use your existing checkout. Extract it and open a terminal in the folder containing requirements-cpu.txt. The beginner ZIP is separate; these lessons use the full repository folder.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txtpy -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txtAfter activation, run the complete worked example from that same folder:
python phases/10-science/01-a-functional-physical-simulation/code/main.py.\.venv\Scripts\python.exe phases/10-science/01-a-functional-physical-simulation/code/main.pyFor an incremental build, create main.py in your own practice folder, append each build block in order, and run python main.py with this environment active. Keep that file separate from the downloaded reference solution.
Download this lesson’s notebook. Open it with a Python kernel using the course environment. Run cells from the top after restarting the kernel; experiments depend on earlier definitions.
For local Jupyter, first install the course requirements using the Local Python steps, then use your environment’s Python to start Jupyter:
python -m pip install jupyterlab
python -m jupyter lab.\.venv\Scripts\python.exe -m pip install jupyterlab
.\.venv\Scripts\python.exe -m jupyter labSelect the downloaded science-01.ipynb file in JupyterLab. The notebook contains reference solutions; make your prediction and attempt each practice task before opening them. Restart the kernel before changing logical device setup.
The worked reference for this lesson is CPU-validated. Some references explicitly configure logical CPU devices; setting JAX_PLATFORMS does not adapt them to a TPU. Follow the execution matrix and reviewed multi-host example before attempting a target run.
For accelerator preparation, study TPU setup, observed runtime receipts, checkpointed jobs and precision and retained traces. Current receipts cover bounded v5e1 launch, resume, and precision checks; four single-device Pallas cases; and a four-device v5e collective fixture. Each receipt is limited to its recorded source, environment, cases, and hardware. It does not qualify all lessons or TPU configurations. Cloud provisioning is optional for CPU learning.
Check: Euler final 0.3570125; analytic final 0.49319393. The endpoint errors decrease as the step is halved.
Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.
What you will be able to do
- Implement a pure scalar state transition with units and a fixed time grid.
- Separate a discrete implementation oracle from continuous approximation error.
- Demonstrate convergence and diagnose loss of stability.
The problem
A hot object cools toward its surroundings. Can we predict its remaining excess temperature two seconds later, and tell a coding bug from a time-step error? We will build a small physical simulation, compare it with two independent references, and deliberately choose an unstable step.
The idea
A numerical solver approximates a continuous process with discrete steps. A program can implement its update rule correctly and still differ from the physical solution. Check implementation error and discretization error separately.
Separate a correct program from an accurate solver
For , one Euler step from with gives , while the continuous solution at the same time is . That gap is the expected error from holding the starting slope fixed over the interval; it is not by itself evidence of a coding mistake.
Two steps of give at the same time. The finer result is closer here because the slope is refreshed more often. Compare values at equal physical time, then compare the program with the exact discrete recurrence to catch implementation errors separately from solver error.
Start with units and one step
The derivative gives change per second. Multiplying by a time step in seconds produces a change in temperature, which can be added to the current state. With , and , the first change is , so Euler predicts . The exact value at that time is about : the slope becomes less negative as the object cools, but Euler holds the initial slope for the whole step.
Keep state explicit and keep the initial observation
The transition receives rate, current state and step length. It never changes a global variable. scan carries the state through time and saves the returned observations. Our output includes , so its shape is for updates. Forgetting the initial observation shifts every comparison by one time step. Float64 is enabled before array construction to make small numerical differences visible on CPU; this lesson makes no accelerator throughput claim.
Use two references because they answer different questions
Repeated multiplication gives the exact answer for the implemented Euler recurrence, , so it can detect an indexing or update bug without using a second loop. The physical equation instead has solution . At two seconds in the recorded run, Euler with gives , while the continuous reference gives . The program matches its discrete oracle, yet the solver underestimates the remaining excess temperature.
Accuracy and stability are different requirements
The multiplier controls every update. Its magnitude must be below one for decay: . To preserve nonnegative temperature excess at every step we need the stronger bound . When , the numerical result alternates sign while its magnitude shrinks. At , its magnitude grows, even though the actual physical solution always decays. A finite output and a differentiable program are separate from a faithful simulation.
Make a convergence table before fitting parameters
Fix the physical horizon at two seconds, halve the time step and double the number of updates. Otherwise you change the question as well as the algorithm. The endpoint error should shrink roughly by a factor of two for this first-order method once the grid is reasonably fine. Convergence toward an analytic solution is evidence for this equation and parameter range; stiff systems, events and discontinuities need different tests.
A correct Euler program still has time-step error
Predict before looking: Will halving the step make the endpoint move toward or away from the analytic curve?
Read the figure
The horizontal axis is elapsed time in seconds and the vertical axis is excess temperature. The coarse Euler curve takes four 0.5-second steps; the finer Euler curve takes eight 0.25-second steps and is sampled at the coarse curve's times. The analytic exponential is evaluated at those same times. All three start at 2. At 2 seconds the plotted endpoints are 0.3570, 0.4292 and 0.4932 for coarse Euler, finer Euler and the analytic curve, respectively.
Connect it to the computation
The gap from coarse Euler to the analytic endpoint is about 0.1362; halving the step reduces it to about 0.0640, roughly the expected first-order trend. The geometric Euler oracle verifies the update was implemented as specified, while the exponential measures the continuous-model error. If the step were made so large that , the numerical multiplier would have magnitude above one and the plotted values would grow even though the physical solution decays.
Figure data and execution details
Open full-size figureDownload data and provenance
The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.
Your build: Create a separate main.py in your practice folder. Append each block in order and run python main.py in the lesson environment. The downloaded script is the complete reference, so keep it separate from your attempt.
1 Define a state transition
Append this block to main.py in your CPU course environment; for the first block create the file. Run blocks in order.
# Step 1 — Define a state transition: A scalar state enters and a new scalar leaves.
import jax
# Enable 64-bit arithmetic before importing jax.numpy or creating arrays.
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
import numpy as np
def euler_step(rate, value, dt):
return value - dt*rate*value
# Define `euler_solve(rate, initial, steps, dt)` to carry state across steps with `jax.lax.scan`:
def euler_solve(rate, initial, steps, dt):
def advance(value, unused):
updated = euler_step(rate, value, dt)
return updated, updated
_, tail = jax.lax.scan(advance, initial, None, length=steps)
return jnp.concatenate((jnp.atleast_1d(initial), tail))A scalar state enters and a new scalar leaves. The initial value is saved explicitly, so a solve with four updates contains five observations. The step count is a Python integer, determining a fixed output shape.
Explain the APIs in this step
jax.lax.scan(step_fn, init_carry, xs, length=...): Compiles a sequential loop whose step returns(next_carry, y), yielding(final_carry, stacked_ys).
2 Compare the simulation with a physical reference
Append this block to main.py in your CPU course environment; for the first block create the file. Run blocks in order.
# Step 2 — Compare the simulation with a physical reference: The geometric sequence verifies implementation correctness.
rate, initial, dt, steps = 0.7, jnp.array(2.0), 0.5, 4
trajectory = euler_solve(rate, initial, steps, dt)
times = np.arange(steps+1)*dt
continuous = 2.0*np.exp(-rate*times)
discrete = 2.0*(1-rate*dt)**np.arange(steps+1)
np.testing.assert_allclose(trajectory, discrete, rtol=1e-12, atol=1e-12)
assert np.all(np.diff(np.asarray(trajectory)) < 0)
assert abs(float(trajectory[-1])-continuous[-1]) > 0.1
print("Euler final:", float(trajectory[-1]), "analytic final:", continuous[-1])The geometric sequence verifies implementation correctness. The exponential checks approximation error. Passing the first comparison does not make the numerical model exact.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.np.testing.assert_allclose(actual, desired, rtol=..., atol=...): Checks a host-side numerical expectation and raisesAssertionErrorwhen values differ beyond tolerance.
3 Refine the time grid without changing the experiment
Append this block to main.py in your CPU course environment; for the first block create the file. Run blocks in order.
# Step 3 — Refine the time grid without changing the experiment: Every run stops at the same physical time.
grid_sizes = np.array([4, 8, 16, 32])
endpoint_errors = np.array([abs(float(euler_solve(rate, initial, int(n), 2.0/n)[-1])-continuous[-1]) for n in grid_sizes])
assert np.all(np.diff(endpoint_errors) < 0)
assert 1.7 < endpoint_errors[-2]/endpoint_errors[-1] < 2.3
print("Endpoint errors:", endpoint_errors)
print("Last refinement ratio:", endpoint_errors[-2]/endpoint_errors[-1])Every run stops at the same physical time. Halving the step approximately halves the global error, as expected for forward Euler on this smooth problem.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
# Step 1 — Define a state transition: A scalar state enters and a new scalar leaves.
import jax
# Enable 64-bit arithmetic before importing jax.numpy or creating arrays.
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
import numpy as np
def euler_step(rate, value, dt):
return value - dt*rate*value
# Define `euler_solve(rate, initial, steps, dt)` to carry state across steps with `jax.lax.scan`:
def euler_solve(rate, initial, steps, dt):
def advance(value, unused):
updated = euler_step(rate, value, dt)
return updated, updated
_, tail = jax.lax.scan(advance, initial, None, length=steps)
return jnp.concatenate((jnp.atleast_1d(initial), tail))
# Step 2 — Compare the simulation with a physical reference: The geometric sequence verifies implementation correctness.
rate, initial, dt, steps = 0.7, jnp.array(2.0), 0.5, 4
trajectory = euler_solve(rate, initial, steps, dt)
times = np.arange(steps+1)*dt
continuous = 2.0*np.exp(-rate*times)
discrete = 2.0*(1-rate*dt)**np.arange(steps+1)
np.testing.assert_allclose(trajectory, discrete, rtol=1e-12, atol=1e-12)
assert np.all(np.diff(np.asarray(trajectory)) < 0)
assert abs(float(trajectory[-1])-continuous[-1]) > 0.1
print("Euler final:", float(trajectory[-1]), "analytic final:", continuous[-1])
# Step 3 — Refine the time grid without changing the experiment: Every run stops at the same physical time.
grid_sizes = np.array([4, 8, 16, 32])
endpoint_errors = np.array([abs(float(euler_solve(rate, initial, int(n), 2.0/n)[-1])-continuous[-1]) for n in grid_sizes])
assert np.all(np.diff(endpoint_errors) < 0)
assert 1.7 < endpoint_errors[-2]/endpoint_errors[-1] < 2.3
print("Endpoint errors:", endpoint_errors)
print("Last refinement ratio:", endpoint_errors[-2]/endpoint_errors[-1])Run the example
python3 phases/10-science/01-a-functional-physical-simulation/code/main.pyAbout this command
This shortcut uses an activated macOS/Linux course environment in the repository folder. For Windows, use the explicit interpreter command in “Setup help” above. The script includes worked examples and reference solutions.
Inspect the complete assembled example
# Step 1 — Define a state transition: A scalar state enters and a new scalar leaves.
import jax
# Enable 64-bit arithmetic before importing jax.numpy or creating arrays.
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
import numpy as np
def euler_step(rate, value, dt):
return value - dt*rate*value
# Define `euler_solve(rate, initial, steps, dt)` to carry state across steps with `jax.lax.scan`:
def euler_solve(rate, initial, steps, dt):
def advance(value, unused):
updated = euler_step(rate, value, dt)
return updated, updated
_, tail = jax.lax.scan(advance, initial, None, length=steps)
return jnp.concatenate((jnp.atleast_1d(initial), tail))
# Step 2 — Compare the simulation with a physical reference: The geometric sequence verifies implementation correctness.
rate, initial, dt, steps = 0.7, jnp.array(2.0), 0.5, 4
trajectory = euler_solve(rate, initial, steps, dt)
times = np.arange(steps+1)*dt
continuous = 2.0*np.exp(-rate*times)
discrete = 2.0*(1-rate*dt)**np.arange(steps+1)
np.testing.assert_allclose(trajectory, discrete, rtol=1e-12, atol=1e-12)
assert np.all(np.diff(np.asarray(trajectory)) < 0)
assert abs(float(trajectory[-1])-continuous[-1]) > 0.1
print("Euler final:", float(trajectory[-1]), "analytic final:", continuous[-1])
# Step 3 — Refine the time grid without changing the experiment: Every run stops at the same physical time.
grid_sizes = np.array([4, 8, 16, 32])
endpoint_errors = np.array([abs(float(euler_solve(rate, initial, int(n), 2.0/n)[-1])-continuous[-1]) for n in grid_sizes])
assert np.all(np.diff(endpoint_errors) < 0)
assert 1.7 < endpoint_errors[-2]/endpoint_errors[-1] < 2.3
print("Endpoint errors:", endpoint_errors)
print("Last refinement ratio:", endpoint_errors[-2]/endpoint_errors[-1])Expected result: Euler final 0.3570125; analytic final 0.49319393. The endpoint errors decrease as the step is halved.
Recorded output and runtime details
Reference output captured from executing the complete lesson script (code/main.py) and its assertions in the course CPU environment.
Euler final: 0.3570125000000001 analytic final: 0.493193927883213
Endpoint errors: [0.13618143 0.06399208 0.03107265 0.0153167 ]
Last refinement ratio: 2.0286780018480166
Euler final: 0.3570125000000001 analytic final: 0.493193927883213
Endpoint errors: [0.13618143 0.06399208 0.03107265 0.0153167 ]
Last refinement ratio: 2.0286780018480166
Stable but sign-alternating: [ 2. -0.8 0.32 -0.128 0.0512]
Unstable numerical endpoint: 3.543121999999993
Changed rate, initial state and grid verified
Energy checks distinguish growth, but not sign preservation
Same-horizon errors: [np.float64(0.050590770107151406), np.float64(0.02471618055802971), np.float64(0.012218898970361547)]
PASS: science-01
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Stable does not mean physically positive
# Experiment — Stable does not mean physically positive
oscillatory = euler_solve(0.7, jnp.array(2.0), 4, 2.0)
np.testing.assert_allclose(oscillatory, [2.0, -0.8, 0.32, -0.128, 0.0512], atol=1e-12)
print("Stable but sign-alternating:", np.asarray(oscillatory))Expected: [2, -0.8, 0.32, -0.128, 0.0512]
The magnitude decays because , but crossing below ambient repeatedly is an artifact of this explicit update.
Reproduce numerical instability
# Experiment — Reproduce numerical instability: The multiplier is -1.1.
unstable = euler_solve(0.7, jnp.array(2.0), 6, 3.0)
assert abs(float(unstable[-1])) > 2.0
assert 2*np.exp(-0.7*18) < 1e-4
print("Unstable numerical endpoint:", float(unstable[-1]))Expected: The numerical magnitude grows above its initial value; the analytic endpoint is near zero.
The multiplier is . Reducing the time step repairs this discretization; clipping negative values would hide the defect and change the model.
Make it yours
Where to put your code: Modify your own main.py, or use the Make it yours cell in your downloaded notebook. Run your attempt in the declared environment and verify your prediction before opening the reference solution.
Change the rate to , the initial excess to , and use twenty steps of seconds. Verify the full discrete trajectory and bound the endpoint error against the exponential.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- Initial excess 5.0, rate 0.3, step size 0.1, and twenty explicit-Euler steps.
Outputs
- Full discrete state trajectory and the analytic exponential trajectory.
- An endpoint-error bound relative to the exponential solution at the matching final time.
Invariants to check
- Each update uses the previous state.
- The endpoint uses the same physical time for both methods.
Hints
- Record the initial value before applying any step.
- Compare discrete updates with exp(-rate * time), including the final time.
import numpy as np
def compare_euler_and_exponential(initial, rate, dt, steps):
# TODO: return times, discrete trajectory, and analytic values.
raise NotImplementedError("Build both trajectories on the same time grid")Reveal the reference solution
# Exercise solution
changed = euler_solve(0.3, jnp.array(5.0), 20, 0.1)
reference = 5.0*(1-0.3*0.1)**np.arange(21)
np.testing.assert_allclose(changed, reference, rtol=1e-12)
assert float(changed[0]) == 5.0
assert abs(float(changed[-1])-5*np.exp(-0.6)) < 0.03
print("Changed rate, initial state and grid verified")Energy does not check every invariant
Practice
Construct an energy diagnostic . Test a monotone stable grid and an unstable grid, and explain why decreasing energy alone does not guarantee a nonnegative state.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- A stable and an unstable explicit-Euler step size for scalar decay.
Outputs
- Energy histories and state-sign checks for both runs.
Invariants to check
- Energy E=u²/2 can decrease even after the state crosses below zero.
- Stability and nonnegativity are separate properties.
Hints
- Track signed state as well as its square.
- Use a step large enough to cross zero but remain within a simple decay example.
import numpy as np
def energy_diagnostics(initial, rate, step_sizes, steps):
# TODO: simulate each grid and return state and energy histories.
raise NotImplementedError("Check signed-state and energy invariants separately")Show a hint
Compare successive squared magnitudes. The sign-alternating case from the experiment still loses energy.
Reveal reference solution and reasoning
# Energy does not check every invariant (Practice)
for h in (0.5, 2.0):
u = np.asarray(euler_solve(0.7, jnp.array(2.0), 6, h))
assert np.all(np.diff(u*u/2) < 0)
u = np.asarray(euler_solve(0.7, jnp.array(2.0), 6, 3.0))
assert np.all(np.diff(u*u/2) > 0)
print("Energy checks distinguish growth, but not sign preservation")A scalar diagnostic can establish decay without capturing every physical invariant. Preserve sign checks separately.
Keep the physical horizon fixed
Challenge
A colleague reports lower error after reducing both the step and number of updates. Reconstruct the final time for each run and repair the comparison.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Two step-size/update-count pairs and a fixed physical decay problem.
Outputs
- Final physical time and endpoint error for each configuration.
Invariants to check
- A fair accuracy comparison uses the same final time.
- Changing the step count changes the horizon unless dt*steps stays fixed.
Hints
- Compute the horizon before comparing endpoint values.
- Use the exponential solution at each run’s actual horizon.
import numpy as np
def compare_horizons(initial, rate, runs):
# TODO: for each (dt, steps), compute its horizon and endpoint error.
raise NotImplementedError("Separate discretization error from a changed horizon")Show a hint
The horizon is number of updates multiplied by step length.
Reveal reference solution and reasoning
# Keep the physical horizon fixed (Challenge)
horizon = 2.0
errors = []
for n in (10, 20, 40):
h = horizon/n
final = euler_solve(0.7, jnp.array(2.0), n, h)[-1]
errors.append(abs(float(final)-2*np.exp(-0.7*horizon)))
assert errors[2] < errors[1] < errors[0]
print("Same-horizon errors:", errors)A refinement study must hold the modeled experiment fixed; comparing different end times conflates physical change and numerical accuracy.
Diagnose the result
If outputs alternate sign, inspect before editing the physical rate. If the curve has the right shape but every point is shifted, compare the saved initial point and time indexing. If a refinement study improves unpredictably, verify that every run ends at the same physical time.
Carry forward
- Start with units and one step
- Keep state explicit and keep the initial observation
- Use two references because they answer different questions
- Accuracy and stability are different requirements
- Make a convergence table before fitting parameters
Keep your evidence
Full geometric/exponential comparisons, fixed-horizon refinement table, unstable-step failure and repair. Keep the environment, observed outputs and your explanation of the figure.
Save your modified code, its output, and an explanation of your prediction. Checkpoint answers and exercise evidence are tracked separately.
Saved in this browser. Export or back up your portfolio anytime in My learning.
Reference execution: CPU validation only. This worked reference is validated on CPU. Accelerator compatibility requires a separate source review and target execution receipt. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.