BSCS and Engineering students taking a Modeling and Simulation or Computational Science elective course can read the complete textbook “Modeling and Simulation in Python” by Allen B. Downey, free from its official source, Green Tea Press. It’s a 27-chapter book, designed for people who have not programmed before, that teaches Python and computational modeling together by building working simulations of population growth, epidemics, physiology, and mechanics.
This edition works through a complete modeling toolkit — from state-based simulation and parameter sweeps, through growth and epidemic models, to physiology and mechanics — closing with a look at how the book’s own modsim library is built on established numerical methods, making it a practical, hands-on companion for anyone who wants to learn simulation by building real, working models rather than through abstract theory alone.
Book Overview
| Course | Modeling and Simulation / Computational Science |
| Degree Programs | BSCS, Engineering, and any program’s Modeling and Simulation, Computational Science, or Python-based science elective course |
| Level | University — beginner to intermediate, designed for people who have not programmed before |
| Edition | 1st Edition (Modeling and Simulation in Python, Green Tea Press / No Starch Press) |
| Author | Allen B. Downey |
| Structure | 27 chapters in three parts — Chapters 1–10 cover population growth modeling, Chapters 11–19 cover epidemiology and physiology, and Chapters 20–27 cover mechanics, closing with a look at how the book’s own modsim library works |
| Exercises | Each chapter is built around a working Jupyter notebook using the author’s own modsim Python library, available on the official site |
| Language | English |
| License | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) — Model: Link-only |
| Format | Free, complete browsable HTML edition (no official free PDF) |
Chapter List
Chapter 1: Modeling
Difficulty: Beginner · Modeling and Simulation — Week 1 · Key topics: What a model is, abstraction, simplifying assumptions, the modeling process, Python and Jupyter setup
This opening chapter introduces what a model is — a deliberately simplified representation of a real system that keeps only the details relevant to the questions being asked — and walks through the general modeling process: choosing what to include, choosing what to leave out, implementing the model in code, and comparing its results against real-world data. It sets up the book’s Python and Jupyter-based workflow used throughout.
Key Points:
- A model is not a complete, exact copy of a real system — it is a deliberately simplified representation that keeps only the details relevant to the specific questions being asked, discarding the rest.
- Every model involves simplifying assumptions, and being explicit about which assumptions were made (and why) is as important as the model’s results themselves, since it defines the model’s scope of validity.
- The general modeling process this book follows is iterative: build a first, simple version of a model, compare its predictions to real data, then decide whether to refine the model or whether it is already good enough for the question at hand.
- This book uses Python together with Jupyter notebooks and the author’s own modsim library throughout, letting a model’s equations, code, and results live together and be modified interactively.
- No single model is “correct” in an absolute sense — a model is judged by whether it is useful for answering the specific questions it was built to answer, not by how completely it captures every detail of the real system.
Practice Tip: Before building any model in this book, explicitly write down what real-world question the model is meant to answer — keeping that question in view makes it much easier to judge which simplifying assumptions are reasonable and which would throw away something essential.
Common Mistake: Judging a model as “wrong” simply because it leaves out real-world details — every model necessarily simplifies reality; the right question is not whether a model is complete, but whether it is useful and accurate enough for the specific question it was built to answer.
Important Questions:
- Q1: What is a model, as this chapter defines it, and why must every model involve simplifying assumptions? A model is a deliberately simplified representation of a real system that keeps only the details relevant to a specific set of questions. It must involve simplifying assumptions because a real system is far too complex to represent completely; the modeler must choose what to include and what to leave out based on what the model needs to answer.
- Q2: How does this chapter describe the general modeling process used throughout the book? An iterative process: build a first, simple version of a model, implement it in code, compare its results to real-world data, and then decide whether to refine the model further or whether it is already good enough for the question being asked.
Chapter 2: Bike Share System
Difficulty: Beginner · Modeling and Simulation — Week 1–2 · Key topics: State variables, a first discrete simulation, bikes moving between two stations, using the modsim library’s State object
This chapter introduces the book’s first concrete simulation: a simplified bike-share system with two stations, where bikes move between stations as customers pick up and return them. It introduces state variables (like the number of bikes currently at each station) as the core idea behind a simulation, and shows how the modsim library’s State object is used to track a system’s state as it changes over time.
Key Points:
- A state variable represents one measurable quantity of a system at a given moment — for the bike-share example, the number of bikes currently at each of the two stations.
- A simulation advances a system through time by repeatedly updating its state variables according to simple rules (here, a bike moving from one station to the other), one small step at a time.
- The modsim library’s State object is used to bundle a system’s state variables together into a single, named, updatable object, rather than tracking them as separate loose variables.
- Even this simple two-station bike-share model can already answer useful questions, like how often a station runs out of bikes, given some assumed rate of customer arrivals at each station.
- This chapter’s step-by-step state-update approach — move forward one small time step, update the state, repeat — is the same basic simulation pattern reused and extended throughout the rest of the book.
Practice Tip: Before adding any randomness to the bike-share model, trace through a few update steps by hand with fixed numbers of bikes at each station — seeing exactly how the state changes step by step makes the more complex, randomized version much easier to reason about later.
Common Mistake: Confusing a system’s state variables with the system itself — the State object holds a snapshot of the relevant numbers (like bikes per station) at one moment in time; the simulation’s real work is the set of rules that update those numbers from one time step to the next.
Important Questions:
- Q1: What is a “state variable” in the context of this chapter’s bike-share model? A state variable is one measurable quantity that describes the system at a given moment — for the bike-share example, the number of bikes currently present at each of the two stations.
- Q2: What is the modsim library’s State object used for in this chapter? It bundles a system’s state variables together into a single, named object that can be updated as the simulation progresses, rather than requiring the state to be tracked as separate, unrelated variables.
Chapter 3: Iteration
Difficulty: Beginner · Modeling and Simulation — Week 2 · Key topics: For loops for simulation, running a model over many time steps, storing results in a TimeSeries
This chapter formalizes the step-by-step simulation pattern from Chapter 2 into a proper iterative loop, running a model over many time steps and storing the resulting values in a TimeSeries object at each step. It shows how a for loop, combined with a state-update function, is enough to simulate a system’s behavior over an extended period and produce a complete record of how its state evolved.
Key Points:
- Simulating a system over time is implemented as a for loop: at each iteration, the current state is updated according to the model’s rules, and the new state becomes the starting point for the next iteration.
- A TimeSeries object (from the modsim library) is used to record a chosen state variable’s value at every time step, producing a complete record of how that quantity changed over the course of the simulation.
- Separating the update logic (a function that computes the next state from the current one) from the iteration loop (which just calls that function repeatedly) makes the simulation’s code cleaner and the update rule easier to test and modify independently.
- Once a simulation’s results are stored in a TimeSeries, they can be plotted directly, letting a modeler visually inspect how a state variable evolved over the whole simulated period at a glance.
- This chapter’s loop-plus-TimeSeries pattern becomes the standard structure used to run essentially every simulation in the rest of the book, from population growth to epidemics to mechanics.
Memory Tip: Keep the loop’s job and the update function’s job mentally separate: the update function answers “what happens in one time step,” while the loop’s only job is “do that, over and over, and record what happened” — conflating the two makes simulation code much harder to debug.
Common Mistake: Forgetting to record (or overwriting) the state at each time step inside the loop — without properly recording each step’s value into the TimeSeries, the simulation still runs correctly internally, but there is no record left afterward showing how the state actually evolved over time, making the results impossible to plot or analyze.
Important Questions:
- Q1: What is the basic loop structure this chapter uses to run a simulation over many time steps? A for loop where, at each iteration, the current state is updated according to the model’s rules to produce the next state, and that new state becomes the input to the next iteration — repeating this update step by step advances the simulation through time.
- Q2: What is a TimeSeries used for in this chapter, and why is it useful? A TimeSeries records the value of a chosen state variable at each time step of the simulation, building up a complete history of how that quantity changed over time. It is useful because it lets the results be plotted and analyzed after the simulation finishes running.
Chapter 4: Sweeping Parameters
Difficulty: Intermediate · Modeling and Simulation — Week 2–3 · Key topics: Parameter sweeps, running a model repeatedly with different inputs, sensitivity analysis, SweepSeries
This chapter introduces parameter sweeps: running the same simulation model repeatedly, each time with a different value for one input parameter, to see how the model’s outcome changes as that parameter varies. Using the bike-share model as the running example, it shows how a SweepSeries object collects each run’s final result against the parameter value used, revealing the relationship between an input assumption and the model’s output.
Key Points:
- A parameter sweep runs the same model multiple times, systematically varying one input parameter across a range of values, in order to see how sensitive the model’s results are to that particular assumption.
- A SweepSeries object stores the outcome of each run indexed by the parameter value that produced it, turning a series of separate simulation runs into a single dataset that shows the input-output relationship directly.
- Sweeping a parameter is a general technique for exploring “what if” questions — for the bike-share model, for example, sweeping the customer arrival rate reveals how quickly a station’s bike shortage worsens as demand increases.
- This chapter’s parameter-sweep technique is distinct from, and complementary to, running a single simulation once: a single run answers “what happens under these specific assumptions,” while a sweep answers “how does the outcome change as one assumption changes.”
- Parameter sweeps become an essential tool throughout the rest of the book for questions like finding an optimal input value or identifying a threshold at which a model’s qualitative behavior changes.
Practice Tip: Before running a full parameter sweep, run the underlying model manually for just two or three very different parameter values and compare the outcomes by hand — this builds intuition for what pattern the full sweep should reveal, making it easier to spot a bug if the sweep’s results look wrong.
Common Mistake: Running a parameter sweep without first confirming that the single underlying model run works correctly — a sweep is only as trustworthy as the individual simulation it repeats; running a buggy model many times with different parameters just produces many differently-wrong results, not a useful sweep.
Important Questions:
- Q1: What does it mean to “sweep” a parameter, as covered in this chapter? Running the same simulation model multiple times, each time using a different value for one chosen input parameter, in order to observe how the model’s outcome changes as that parameter varies across a range of values.
- Q2: What is the difference between a single simulation run and a parameter sweep, in terms of what question each answers? A single run answers “what happens under one specific set of assumptions.” A parameter sweep answers a broader question: “how does the outcome change as one particular assumption is varied,” by collecting the results of many single runs into one dataset indexed by the swept parameter.
Chapter 5: World Population
Difficulty: Intermediate · Modeling and Simulation — Week 3 · Key topics: Historical world population data, reading real data with pandas, plotting a time series
This chapter shifts from simulation to real-world data, introducing historical world population figures as the case study for the book’s next several chapters on growth modeling. It covers reading population data into a pandas Series, plotting it to visually inspect its shape over time, and previews the qualitative question the next few chapters will address: what kind of mathematical growth model best matches this real data.
Key Points:
- This chapter works with real historical world population data (spanning many centuries), read into a pandas Series, marking the book’s shift from purely hypothetical models to modeling a genuine, measured real-world quantity.
- Plotting the raw population data over time reveals its overall shape — slow growth for a very long historical period, followed by a dramatic acceleration in the more recent past — which becomes the pattern the next several chapters try to explain with different growth models.
- Working with real data introduces practical concerns absent from purely synthetic simulations, such as missing values, inconsistent units across different historical sources, and deciding on an appropriate time range to analyze.
- This chapter deliberately does not yet propose a growth model to explain the population data — it establishes the real data as a benchmark first, against which the constant-growth, proportional-growth, and logistic-growth models of the following chapters will each be compared.
- The pandas Series introduced here for handling real population data is used alongside the modsim library’s own TimeSeries and SweepSeries objects throughout the rest of the book whenever real historical data needs to be compared against simulated model output.
Memory Tip: Before jumping into the growth models of the next few chapters, spend real time just looking at the plotted population curve from this chapter and describing its shape in plain words (slow, then fast) — having that description in mind makes it much easier to judge whether each upcoming model’s predicted shape actually matches reality.
Common Mistake: Treating this chapter’s real population data as if it were itself a model — the data is simply the measured historical record used as a benchmark; the actual explanatory models (constant growth, proportional growth, logistic growth) are built in the chapters that follow and are judged by how well they reproduce this data, not the other way around.
Important Questions:
- Q1: What is this chapter’s main purpose, given that it does not yet introduce a growth model? To introduce and plot real historical world population data as a benchmark, establishing its overall shape (slow growth historically, then a recent acceleration) that the growth models introduced in the following chapters will each be tested against.
- Q2: What practical concerns does working with real population data introduce that a purely hypothetical simulation, like the bike-share model, does not have? Concerns like missing values, inconsistent units or measurement methods across different historical sources, and choosing an appropriate time range to analyze — issues that simply do not arise when working with a fully synthetic, hypothetical model.
Chapter 6: Proportional Growth
Difficulty: Intermediate · Modeling and Simulation — Week 3–4 · Key topics: Constant growth rate models, exponential growth, comparing a proportional-growth model to real population data
This chapter proposes the first real growth model for world population: proportional growth, where the population’s annual increase is assumed to be a constant fraction of its current size, producing exponential growth. It implements this model as a simulation, compares its predictions against the real historical data from the previous chapter, and shows where the simple proportional-growth assumption starts to diverge from reality.
Key Points:
- A proportional-growth model assumes the population’s growth in each time step is a constant fraction (growth rate) of the population’s current size, which mathematically produces exponential growth over time.
- Implementing proportional growth as a simulation uses the exact same loop-plus-state-update pattern from Chapter 3: at each step, compute the population increase as (growth rate × current population) and add it to get the next value.
- Comparing the proportional-growth model’s simulated curve against the real historical population data from Chapter 5 shows a reasonably good match for some historical periods, but the model’s exponential shape eventually diverges noticeably from the real data’s actual trajectory.
- The specific growth rate used in the model can itself be estimated from the real data (for example, by fitting the model to an early portion of the historical record), rather than being chosen arbitrarily.
- This chapter’s mismatch between the proportional-growth model and the full historical record is used deliberately to motivate the following chapters, which introduce more refined growth models (like the logistic model in Chapter 7) that better capture real population dynamics.
Practice Tip: Run the proportional-growth model with two or three different growth rates and overlay all three curves against the real historical data on one plot — seeing directly how sensitive the model’s long-term shape is to this single parameter makes the exponential growth assumption’s limitations concrete.
Common Mistake: Assuming a proportional-growth (exponential) model must be a poor model simply because it eventually diverges from the real long-run population data — the model can still be a good, useful approximation over a shorter historical period; a model doesn’t need to be universally correct across all time scales to be useful for a specific question or period.
Important Questions:
- Q1: What is the core assumption of the proportional-growth model introduced in this chapter? That the population’s growth in each time step is a constant fraction (a fixed growth rate) of the population’s current size — this assumption mathematically produces exponential growth over time.
- Q2: How does this chapter’s comparison between the proportional-growth model and the real historical data set up the chapters that follow? By showing that while the proportional-growth model matches reasonably well for some historical periods, its exponential shape eventually diverges from the actual trajectory of the real data — this mismatch motivates the more refined growth models, like the logistic growth model, introduced in the following chapters.
Chapter 7: Limits to Growth
Difficulty: Intermediate · Modeling and Simulation — Week 4 · Key topics: Carrying capacity, the logistic growth model, how growth rate slows as population approaches a limit
This chapter introduces the logistic growth model, which refines the proportional-growth model from the previous chapter by adding a carrying capacity — an upper limit the population approaches but does not exceed, as growth slows the closer the population gets to that limit. It shows how this single added assumption produces a characteristic S-shaped growth curve that matches many real-world growth phenomena, including population, more closely than unlimited exponential growth.
Key Points:
- The logistic growth model modifies proportional growth by making the growth rate itself decrease as the population approaches a carrying capacity (an assumed maximum sustainable population size), rather than staying constant forever.
- As the population gets closer to the carrying capacity, the model’s growth rate approaches zero, causing the population curve to flatten out near the limit instead of continuing to grow exponentially without bound.
- The resulting logistic growth curve has a characteristic S-shape (sigmoid): slow growth initially, an accelerating middle phase resembling exponential growth, and then a flattening phase as the population approaches the carrying capacity.
- The logistic model introduces one additional parameter beyond the growth rate — the carrying capacity itself — which, like the growth rate, can be estimated by fitting the model to real historical data.
- This chapter’s logistic model is a foundational pattern reused later in the book, most directly in the epidemiology chapters, where a population of susceptible individuals plays a role structurally similar to a carrying capacity that an epidemic’s spread approaches.
Memory Tip: Remember the logistic model’s core difference from proportional growth in one line: proportional growth assumes a constant growth RATE, while logistic growth assumes that rate itself shrinks toward zero as the population approaches its carrying capacity — that single change is what produces the characteristic S-shaped curve instead of unbounded exponential growth.
Common Mistake: Treating the carrying capacity as a hard ceiling the population can never cross under any circumstances, rather than as a model parameter representing an assumed sustainable limit — the carrying capacity is itself an estimated, adjustable input to the model, not a law of nature, and different carrying-capacity assumptions produce different logistic curves.
Important Questions:
- Q1: What single change does the logistic growth model make to the proportional-growth model from the previous chapter? It makes the growth rate itself decrease as the population approaches a carrying capacity (an assumed maximum sustainable population size), rather than keeping the growth rate constant forever as the proportional-growth model does.
- Q2: Why does the logistic growth model produce an S-shaped (sigmoid) curve rather than a curve that grows exponentially without bound? Because as the population approaches the carrying capacity, the model’s growth rate approaches zero, causing growth to slow and the curve to flatten out near the limit — this produces the characteristic pattern of slow initial growth, an accelerating middle phase, and a flattening phase near the carrying capacity, rather than continued unbounded exponential growth.
Chapter 8: Projecting Population Growth
Difficulty: Intermediate · Modeling and Simulation — Week 4–5 · Key topics: Using a fitted model to forecast, extrapolating beyond known data, comparing model projections to actual outcomes
This chapter uses the logistic growth model from the previous chapter to actually project future world population, fitting the model to historical data available up to a certain point and then extrapolating forward. It compares these model-based projections against population figures that actually occurred afterward, giving a concrete, honest assessment of how well (or poorly) the model’s forecasts held up.
Key Points:
- Projecting a model into the future means fitting it to data available up to some cutoff point, then extending the model’s equations beyond that cutoff to predict values for times that had not yet occurred when the model was fit.
- This chapter deliberately fits the logistic model using only data available up to an earlier historical cutoff, then compares its resulting projection against the real population figures that were later actually recorded, providing an honest test of the projection’s accuracy.
- Extrapolation is inherently riskier than interpolation: a model that fits well within the range of data it was fit to provides no guarantee that its behavior remains accurate once projected beyond that range, and this chapter’s comparison makes that risk concrete rather than abstract.
- Even a model that fits historical data closely can still produce a poor projection if the real-world system’s underlying dynamics genuinely change after the cutoff point (for example, due to new technologies or policies affecting growth) in ways the model has no way to anticipate.
- This chapter’s practice of testing a model’s real-world forecasting accuracy against actual outcomes, rather than only checking how well it fits data it was trained on, is a broadly important habit for evaluating any predictive model, not just population growth specifically.
Practice Tip: When reproducing this chapter’s projection yourself, deliberately try fitting the model to two different historical cutoff dates and compare how differently each version projects the future — seeing how much a projection can shift based on exactly which historical data was available builds real intuition for extrapolation’s risks.
Common Mistake: Assuming that because a model fits historical data very closely, its future projections must also be accurate — a good fit to past data only shows the model captures the PAST dynamics well; it says nothing about whether those same dynamics will continue to hold in the future, which is exactly the risk this chapter’s honest projection-versus-actual comparison is designed to expose.
Important Questions:
- Q1: What does it mean to “project” a model, as covered in this chapter? Fitting the model’s parameters to real data available up to some cutoff point, then extending the model’s equations forward beyond that cutoff to predict values for a time period that had not yet occurred when the model was fit.
- Q2: Why is extrapolation described as riskier than interpolation in this chapter? Because a model that fits well within the range of data it was trained on provides no guarantee it will remain accurate once projected beyond that range — the real-world system’s underlying dynamics can change in ways the model, fit only to past data, has no way to anticipate.
Chapter 9: Analysis of Population Growth
Difficulty: Advanced · Modeling and Simulation — Week 5 · Key topics: Comparing multiple growth models analytically, quadratic growth, evaluating model fit quantitatively
This chapter steps back to analytically compare the different population growth models covered so far — proportional, logistic, and a newly introduced quadratic growth model — evaluating each one’s fit to the real historical data using quantitative error measures rather than just visual comparison. It reinforces that choosing among competing models is itself a modeling decision, not something with one automatically “correct” answer.
Key Points:
- This chapter introduces quadratic growth as a third competing growth model, alongside the proportional and logistic models from earlier chapters, to be compared against the same real population data.
- Rather than relying only on visually comparing plotted curves, this chapter introduces quantitative error measures (such as the sum of squared differences between a model’s predictions and the real data) to more objectively evaluate how well each candidate model fits.
- No single model among proportional, logistic, and quadratic growth is unconditionally the “best” — each has different strengths depending on which historical period or which quantitative error measure is emphasized.
- This chapter reinforces a recurring theme of the book: selecting among several plausible models is itself a modeling decision requiring judgment, not a step that a single formula or fitting procedure can fully automate away.
- The quantitative model-comparison techniques introduced here for population growth carry over directly to later chapters in the book, where multiple competing models (for example, of an epidemic’s spread) must similarly be compared and evaluated against real data.
Memory Tip: Remember that a lower quantitative error score for one model over another doesn’t automatically make it the “right” choice — also weigh how each model’s assumptions and behavior beyond the fitted data range align with the actual question being asked, not just which curve minimizes one particular error measure.
Common Mistake: Assuming that model comparison always has one objectively correct winner determined purely by which model achieves the lowest fitting error — the choice among competing models also depends on the specific question being asked, the models’ differing assumptions, and how each one is expected to behave outside the range of the data it was fit to.
Important Questions:
- Q1: What third growth model does this chapter introduce alongside proportional and logistic growth? Quadratic growth, added specifically so it can be compared quantitatively against the proportional and logistic growth models covered in earlier chapters, using the same real historical population data.
- Q2: Why does this chapter introduce quantitative error measures instead of relying only on visually comparing plotted model curves? Quantitative error measures (like the sum of squared differences between a model’s predictions and the real data) provide a more objective, comparable way to evaluate how well different candidate models fit the same data, rather than relying on subjective visual judgment of which plotted curve “looks closest” to the real data.
Chapter 10: Case Studies Part 1
Difficulty: Advanced · Modeling and Simulation — Week 5–6 · Key topics: Applying the population-growth modeling toolkit to new case studies, open-ended modeling exercises
This chapter closes out the book’s first part (population and growth modeling) with a set of open-ended case studies that ask readers to apply the modeling tools from Chapters 1–9 — state-based simulation, parameter sweeps, growth models, projection, and quantitative model comparison — to new systems and questions, without being given a pre-built model to follow step by step.
Key Points:
- This chapter is structured as a review-and-application checkpoint rather than introducing new modeling techniques, asking readers to combine tools from the preceding nine chapters (state-based simulation, sweeps, growth models, projection, model comparison) on their own.
- The case studies presented here are deliberately more open-ended than the earlier chapters’ step-by-step walkthroughs, requiring the reader to decide which modeling technique is appropriate for a new, only partially specified problem.
- Working through this chapter’s case studies independently is presented as a genuine test of whether the population-and-growth-modeling toolkit from Part 1 has actually been internalized, not just followed along with passively.
- This chapter marks a structural transition point in the book: it closes the population-and-growth-modeling material before the next several chapters shift the book’s focus to epidemiological and physiological modeling.
- The general modeling discipline emphasized here — explicitly stating assumptions, comparing a model’s output to real data, and judging a model by its usefulness for a specific question — carries forward unchanged into the very different systems modeled in the chapters that follow.
Practice Tip: Attempt this chapter’s case studies before looking at any suggested solution, even if it takes longer or the first attempt is wrong — the real value of a review chapter like this one comes from struggling to decide which technique applies, not from confirming an answer someone else already worked out.
Common Mistake: Skipping this chapter’s case studies because it doesn’t introduce new named techniques — treating a review-and-application chapter as skippable filler misses its actual purpose: applying previously learned tools to new, less-structured problems is a different and essential skill from following a worked example step by step.
Important Questions:
- Q1: What is the main purpose of this chapter, given that it does not introduce new modeling techniques? To let readers apply the population-and-growth-modeling toolkit built up across Chapters 1 through 9 — state-based simulation, parameter sweeps, growth models, projection, and model comparison — to new, more open-ended case studies, testing whether those tools have actually been internalized.
- Q2: What structural role does this chapter play in the book as a whole? It serves as a checkpoint closing out Part 1 of the book (population and growth modeling) before the following chapters shift the book’s focus to epidemiological and physiological modeling topics.
Chapter 11: Epidemiology
Difficulty: Advanced · Modeling and Simulation — Week 6 · Key topics: The SIR model, susceptible/infected/recovered compartments, basic epidemic simulation
This chapter introduces epidemiological modeling with the classic SIR model, which divides a population into three compartments — susceptible, infected, and recovered — and models how individuals move between these compartments over the course of an epidemic. It implements the SIR model as a state-based simulation using the same tools from Part 1 of the book, and uses it to explore how an epidemic grows, peaks, and eventually declines.
Key Points:
- The SIR model divides a population into three compartments: Susceptible (can still catch the disease), Infected (currently sick and contagious), and Recovered (immune, no longer contagious), tracking how the population is distributed among these three groups over time.
- Movement between compartments follows simple rules: susceptible individuals become infected at a rate depending on contact with infected individuals, and infected individuals recover (moving to the recovered compartment) at some fixed recovery rate.
- Implementing the SIR model reuses the exact same state-based simulation pattern from earlier chapters, with the state now consisting of the three compartment sizes (S, I, R) instead of a single population value.
- The SIR model reproduces a realistic epidemic curve: an initial exponential-looking growth phase while susceptible individuals are still plentiful, a peak, and then a decline as the pool of susceptible individuals shrinks and recovered/immune individuals accumulate.
- This chapter’s basic SIR model sets up the following chapters, which extend it with vaccination (Chapter 12), parameter sweeps applied to epidemic parameters (Chapter 13), and simplification via nondimensionalization (Chapter 14).
Memory Tip: Remember the SIR compartments as a one-way flow: Susceptible → Infected → Recovered — in the basic model, individuals move through these compartments in this fixed order and direction, never moving backward from Recovered to Susceptible or from Infected back to Susceptible.
Common Mistake: Assuming the SIR model tracks individual people explicitly — the model actually tracks the aggregate SIZE of each compartment (how many people are susceptible, infected, or recovered overall) as continuous or discrete quantities, not the individual status of each specific person in the population.
Important Questions:
- Q1: What do the three letters S, I, and R stand for in the SIR model, and what does each compartment represent? S stands for Susceptible (individuals who can still catch the disease), I stands for Infected (individuals who are currently sick and contagious), and R stands for Recovered (individuals who are immune and no longer contagious).
- Q2: What basic pattern does the SIR model reproduce when simulating the course of an epidemic? An initial phase of exponential-looking growth in infections while susceptible individuals are still plentiful, followed by a peak, and then a decline in infections as the pool of susceptible individuals shrinks and more people move into the recovered compartment.
Chapter 12: Modeling Vaccination
Difficulty: Advanced · Modeling and Simulation — Week 6–7 · Key topics: Extending the SIR model with vaccination, herd immunity, reducing the susceptible population before an epidemic starts
This chapter extends the basic SIR model from the previous chapter to include vaccination, modeling how moving some fraction of the population directly from susceptible to recovered (immune) before an epidemic begins changes the epidemic’s trajectory. It uses this extended model to explore herd immunity: the phenomenon where vaccinating enough of a population can prevent an epidemic from taking off at all, even among the remaining unvaccinated individuals.
Key Points:
- Vaccination is modeled by moving a chosen fraction of the population directly from the susceptible compartment into the recovered (immune) compartment before the epidemic simulation begins, reflecting immunity gained through vaccination rather than through infection.
- Reducing the initial susceptible population through vaccination directly reduces how many new infections can occur at each step, since new infections in the SIR model depend on contact between susceptible and infected individuals.
- Herd immunity emerges naturally from the model: once the vaccinated fraction is high enough, the susceptible population is reduced so much that an epidemic cannot sustain itself and grow, even without vaccinating every single individual.
- This chapter uses parameter sweeps (from Chapter 4) applied to the vaccination rate to find the approximate herd-immunity threshold — the minimum vaccinated fraction needed to prevent a large-scale outbreak, given the model’s other epidemic parameters.
- The vaccination model built here directly informs real public-health policy questions, illustrating how a relatively simple compartmental model can produce genuinely useful, non-obvious insight (like a specific herd-immunity threshold) from just a few basic assumptions.
Practice Tip: Sweep the vaccination rate from 0% to 100% and plot the resulting peak infection level for each value — watching the peak level drop sharply once the vaccination rate crosses the herd-immunity threshold makes the concept concrete and visually striking rather than abstract.
Common Mistake: Assuming herd immunity requires vaccinating 100% of a population — the whole point of this chapter’s model is that herd immunity can be achieved once vaccination reduces the susceptible population below a specific threshold, well short of the entire population, because the epidemic can no longer sustain enough new infections to grow even among the remaining unvaccinated individuals.
Important Questions:
- Q1: How is vaccination represented in this chapter’s extended SIR model? By moving a chosen fraction of the population directly from the susceptible compartment into the recovered (immune) compartment before the epidemic simulation begins, reflecting immunity gained through vaccination rather than through actually being infected and recovering.
- Q2: What is herd immunity, as this chapter’s model demonstrates it? The phenomenon where, once a high enough fraction of the population is vaccinated (and so moved out of the susceptible compartment), the remaining susceptible population is too small to sustain an epidemic’s growth — preventing a large-scale outbreak even without vaccinating every single individual in the population.
Chapter 13: Sweeping Parameters
Difficulty: Advanced · Modeling and Simulation — Week 7 · Key topics: Applying parameter sweeps to epidemic parameters, exploring contact rate and recovery rate, identifying epidemic thresholds
This chapter revisits the parameter-sweep technique from Chapter 4, now applying it directly to the SIR epidemic model’s own parameters — the contact rate and recovery rate — to explore how these two parameters jointly determine whether an epidemic takes off at all, and how severe it becomes if it does. It shows how sweeping two parameters together can reveal a threshold boundary separating outbreak from no-outbreak scenarios.
Key Points:
- This chapter applies the parameter-sweep technique introduced in Chapter 4 specifically to the SIR model’s contact rate (how readily the disease spreads on contact) and recovery rate (how quickly infected individuals recover).
- Sweeping the contact rate and recovery rate together, rather than one at a time, reveals a two-dimensional threshold boundary in parameter space separating combinations that produce a significant outbreak from combinations where the disease dies out without spreading widely.
- The ratio of the contact rate to the recovery rate (related to what epidemiologists call the basic reproduction number) emerges from this sweep as the key quantity determining whether an epidemic can grow, more informative than either individual rate considered on its own.
- This chapter demonstrates that a two-parameter sweep can answer qualitatively different questions than sweeping a single parameter (as in Chapters 4 and 12) — here the interesting question is not just “how big is the outbreak” but “does an outbreak happen at all.”
- The threshold behavior uncovered in this chapter (a fairly sharp transition between contained and out-of-control epidemic scenarios, depending on the ratio of two rates) is a pattern that recurs in many other systems modeled with compartmental or rate-based equations, well beyond epidemiology specifically.
Memory Tip: Remember the key ratio, not just the two individual rates: it is the relationship between contact rate and recovery rate — not either rate viewed alone — that determines whether this chapter’s swept model predicts a significant outbreak or a disease that fizzles out.
Common Mistake: Sweeping the contact rate and recovery rate independently, one at a time, and expecting to find the same threshold insight as sweeping both together — the epidemic threshold in this chapter emerges specifically from the RELATIONSHIP between the two rates, which only becomes visible when both parameters are swept jointly, not when each is examined in isolation.
Important Questions:
- Q1: What two SIR model parameters does this chapter’s parameter sweep focus on? The contact rate (how readily the disease spreads when a susceptible individual contacts an infected one) and the recovery rate (how quickly infected individuals move into the recovered compartment).
- Q2: What key insight does sweeping the contact rate and recovery rate together reveal, that sweeping either one alone would not? It reveals a threshold boundary in the combined parameter space separating scenarios where a significant outbreak occurs from scenarios where the disease dies out — showing that it is specifically the ratio between the two rates, not either rate considered alone, that determines whether the epidemic can grow.
Chapter 14: Nondimensionalization
Difficulty: Advanced · Modeling and Simulation — Week 8 · Key topics: Removing units from a model’s equations, rescaling variables, simplifying a model to its essential parameters
This chapter introduces nondimensionalization: rewriting a model’s equations in terms of rescaled, unitless variables, so that its essential behavior depends on the fewest possible number of combined parameters rather than several separate ones with physical units. Applied to the SIR epidemic model, this technique reveals that the model’s qualitative behavior actually depends on just one or two combined dimensionless ratios, not every individual rate separately.
Key Points:
- Nondimensionalization rewrites a model’s variables and equations in rescaled, unitless form, often by dividing physical quantities by a characteristic reference value (like population size, or a characteristic time scale) chosen from the model itself.
- A key benefit of nondimensionalizing a model is reducing the number of independent parameters that actually matter: several separate physical parameters can often be combined into just one or two dimensionless ratios that fully determine the model’s qualitative behavior.
- Applied to the SIR model, nondimensionalization confirms and formalizes the finding from the previous chapter’s parameter sweep — that the model’s behavior depends on the ratio of the contact and recovery rates, not on their individual absolute values.
- A nondimensionalized model’s results generalize more easily across different real-world scales (for example, different population sizes or different absolute infection/recovery rates), since its behavior is expressed purely in terms of scale-independent ratios.
- This chapter’s nondimensionalization technique, while introduced here for the SIR model, is a general modeling tool applicable to many of the physical models built later in the book, including the cooling and mechanics chapters.
Practice Tip: Work through nondimensionalizing a simpler model than SIR first (for example, the proportional growth model from Chapter 6) before attempting it on SIR — practicing the rescaling process on a model with just one parameter makes the technique’s mechanics clear before applying it to a model with several interacting rates.
Common Mistake: Treating nondimensionalization as changing what a model predicts — nondimensionalizing a model does not change its underlying behavior at all; it only rewrites the SAME model in rescaled, unitless terms, which can reveal which combinations of parameters actually matter, but does not alter any of the model’s actual predictions.
Important Questions:
- Q1: What does it mean to nondimensionalize a model, as covered in this chapter? Rewriting a model’s variables and equations in rescaled, unitless form, typically by dividing physical quantities by a characteristic reference value drawn from the model itself, so that the model’s behavior is expressed in terms of dimensionless ratios rather than several separate parameters with physical units.
- Q2: What did nondimensionalizing the SIR model confirm about its behavior, connecting back to the previous chapter? It confirmed and formalized the previous chapter’s parameter-sweep finding that the SIR model’s qualitative behavior (whether an outbreak occurs) depends on the ratio of the contact rate to the recovery rate, rather than on the individual absolute values of either rate considered separately.
Chapter 15: Cooling Coffee
Difficulty: Advanced · Modeling and Simulation — Week 8–9 · Key topics: Newton’s law of cooling, a first ordinary differential equation model, comparing a cooling model to real temperature data
This chapter shifts the book’s focus to physical and physiological systems, starting with a simple, classic example: modeling how a cup of coffee cools toward room temperature using Newton’s law of cooling. It implements this as the book’s first explicit ordinary-differential-equation-style model and compares its predicted cooling curve against real measured temperature data.
Key Points:
- Newton’s law of cooling states that an object’s rate of temperature change is proportional to the difference between its current temperature and the surrounding ambient temperature — cooling faster when the difference is large, and slowing as the object approaches ambient temperature.
- This chapter implements Newton’s law of cooling as a state-based simulation using the same loop-plus-update-function pattern established in Chapter 3, now applied to a continuous physical quantity (temperature) instead of a population count.
- The resulting cooling curve has an exponential-decay shape, mathematically related to the proportional-growth model from Chapter 6, but decreasing toward the ambient temperature rather than growing without bound.
- Comparing the model’s predicted cooling curve against real measured coffee-temperature data (read with a thermometer over time) tests the Newton’s-law-of-cooling assumption directly, the same real-data-comparison discipline used for the population models in Part 1.
- This coffee-cooling model sets up the next chapter, which extends it by adding milk at different times, turning a simple single-object cooling model into a comparison of different strategies for a common everyday question.
Memory Tip: Remember Newton’s law of cooling as “rate proportional to the gap”: the bigger the temperature difference between the object and its surroundings, the faster it cools, and that rate shrinks toward zero as the object’s temperature approaches the ambient temperature.
Common Mistake: Assuming an object cools at a constant rate until it reaches ambient temperature — Newton’s law of cooling specifically predicts a rate that is NOT constant: cooling is fastest early on, when the temperature difference from ambient is largest, and slows continuously as the object’s temperature approaches the surrounding ambient temperature.
Important Questions:
- Q1: What does Newton’s law of cooling state, as used in this chapter’s model? That an object’s rate of temperature change is proportional to the difference between its current temperature and the ambient (surrounding) temperature — the object cools faster when that temperature difference is large, and more slowly as its temperature approaches the ambient temperature.
- Q2: How does this chapter test whether Newton’s law of cooling is a good model for a real cup of coffee? By comparing the model’s predicted cooling curve against real measured coffee-temperature data collected with a thermometer over time, following the same real-data-comparison approach used to evaluate the population growth models earlier in the book.
Chapter 16: Adding Milk
Difficulty: Advanced · Modeling and Simulation — Week 9 · Key topics: Extending the cooling model, does adding milk immediately or later keep coffee hotter, comparing two strategies with simulation
This chapter extends the coffee-cooling model from the previous chapter to answer a classic everyday question: if you’re adding cold milk to hot coffee and want it as hot as possible later, should you add the milk immediately, or wait until just before drinking? It models both strategies using the cooling model plus a simple mixing rule, and uses simulation to settle the question definitively.
Key Points:
- This chapter models two competing strategies: adding cold milk to the coffee immediately (letting the mixture cool together) versus waiting to add the milk until just before drinking (letting the black coffee cool alone, then mixing in cold milk right at the end).
- Both strategies reuse the Newton’s-law-of-cooling model from the previous chapter for the cooling phase, combined with a simple instantaneous-mixing rule (a weighted average of temperatures) for the moment milk is added.
- Simulating both strategies side by side and comparing the final temperature at drinking time answers the question directly: adding milk later keeps the coffee hotter at drinking time than adding it immediately, because black coffee (with a bigger temperature gap from ambient) cools faster while it’s hotter, so waiting to cool the mixture together (after adding milk, which lowers the temperature gap) for less time preserves more heat overall.
- This chapter is a clear, concrete example of the book’s broader theme: a genuinely useful, sometimes surprising, real-world answer can come from a fairly simple model, once that model is built carefully and its competing scenarios are compared systematically via simulation, rather than argued about intuitively.
- The strategy-comparison approach used here — simulating two or more competing courses of action under the same underlying model and comparing their outcomes — is reused directly in the mechanics chapters later in the book, particularly the baseball optimization chapters.
Practice Tip: Before running the simulation, predict for yourself which strategy you think keeps the coffee hotter, and write down your reasoning — then compare your prediction against the simulation result; this chapter’s classic answer is often counterintuitive on first thought, which makes it a particularly good test of whether the underlying cooling model is genuinely being understood.
Common Mistake: Assuming the timing of adding milk cannot possibly matter, since “the same amount of milk gets added either way” — this ignores that Newton’s law of cooling makes the RATE of heat loss depend on the current temperature gap from ambient, so which strategy keeps more heat at drinking time depends on how that gap changes over the whole cooling period, not just on the final ingredients mixed together.
Important Questions:
- Q1: What two strategies does this chapter’s model compare regarding when to add milk to coffee? Adding cold milk immediately (letting the milk-coffee mixture cool together from the start) versus waiting to add the milk until just before drinking (letting the black coffee cool alone, then mixing in cold milk right at the end).
- Q2: According to this chapter’s simulation, which strategy keeps the coffee hotter at drinking time, and why? Adding milk later keeps the coffee hotter at drinking time. This happens because, under Newton’s law of cooling, the hotter black coffee (with a larger temperature gap from ambient) loses heat faster while alone; waiting to add milk means the mixture (with a smaller temperature gap after the cold milk lowers it) spends less total time cooling as the combined mixture, preserving more heat overall.
Chapter 17: Pharmacokinetics
Difficulty: Advanced · Modeling and Simulation — Week 9–10 · Key topics: Modeling drug concentration in the body over time, absorption and elimination rates, dosing schedules
This chapter introduces pharmacokinetic modeling: simulating how a drug’s concentration in the body rises after being taken and then falls as the body metabolizes and eliminates it, using simple absorption and elimination rate parameters. It extends this single-dose model to multiple, repeated doses on a schedule, showing how drug concentration can build up (or reach a stable equilibrium level) with regular dosing.
Key Points:
- A basic pharmacokinetic model tracks drug concentration in the body as a state variable, increasing when a dose is absorbed and decreasing continuously as the body eliminates the drug, following rate-based rules similar to the cooling and growth models from earlier chapters.
- Elimination is typically modeled as proportional to the current drug concentration — the same proportional-decrease pattern as Newton’s law of cooling, applied here to a chemical concentration in the body instead of a physical temperature.
- Extending the model to repeated doses (for example, one pill every several hours) shows how a drug’s concentration can build up over several doses before reaching a roughly stable equilibrium level, where the concentration added by each new dose balances the amount eliminated between doses.
- This pharmacokinetic model can be used to explore practical, clinically relevant questions such as how a dosing schedule’s timing and amount affects whether drug concentration stays safely within an effective range, without ever rising to dangerous levels or falling below an effective threshold.
- This chapter’s structural pattern — absorption/increase balanced against a proportional elimination/decrease, extended to a repeated real-world schedule — previews the glucose-insulin model in the very next chapter, which follows a related but more complex two-variable version of the same basic idea.
Memory Tip: Remember the drug-concentration pattern as a balance: concentration rises with each new dose and falls continuously due to elimination, and the equilibrium level reached under a regular dosing schedule is exactly the level where the amount added by each dose balances the amount eliminated between doses.
Common Mistake: Assuming that taking a drug on a regular schedule causes its concentration to keep rising indefinitely with every dose — because elimination in this model is proportional to current concentration, the amount eliminated between doses grows too as concentration rises, so under a steady dosing schedule the concentration approaches a stable equilibrium level rather than growing forever.
Important Questions:
- Q1: How does this chapter’s basic pharmacokinetic model represent drug elimination from the body? As proportional to the drug’s current concentration — the same proportional-decrease pattern used for Newton’s law of cooling in Chapter 15, here applied to a chemical concentration in the body rather than a physical temperature.
- Q2: What happens to drug concentration over time when this model is extended to a repeated, regular dosing schedule? Concentration builds up over the first several doses and then approaches a roughly stable equilibrium level, at which the amount of drug added by each new dose balances the amount eliminated between doses, rather than rising without bound indefinitely.
Chapter 18: Glucose and Insulin
Difficulty: Advanced · Modeling and Simulation — Week 10 · Key topics: The minimal model of glucose-insulin dynamics, two interacting state variables, fitting a physiological model to clinical data
This chapter extends the single-variable pharmacokinetic modeling approach to a genuinely two-variable physiological system: the interaction between blood glucose and insulin levels after a meal, using a simplified version of the well-known “minimal model” from the diabetes research literature. It shows how two coupled state variables, each affecting the other’s rate of change, can be simulated together and fit against real clinical glucose-insulin measurement data.
Key Points:
- This chapter’s minimal model tracks two interacting state variables simultaneously: blood glucose concentration and blood insulin concentration, each of whose rate of change depends partly on the other variable’s current value.
- Insulin’s role in the model is to help remove glucose from the bloodstream (glucose’s rate of change depends on the current insulin level), while glucose’s role is to stimulate the body to release more insulin (insulin’s rate of change depends on the current glucose level) — a coupled, two-way relationship rather than one variable simply driving the other.
- Simulating two coupled state variables together, rather than one variable at a time, requires updating both variables’ next values using each other’s CURRENT values at each time step, extending the single-variable update pattern from earlier chapters to a genuinely interacting two-variable system.
- This chapter fits the minimal model’s parameters against real clinical data (glucose and insulin measurements taken from an actual patient after a test meal), following the same real-data-fitting discipline used for population growth and coffee cooling earlier in the book.
- The minimal model covered in this chapter is a real, historically significant model from the diabetes research literature, illustrating that the book’s core simulation techniques scale up directly from toy examples like coffee cooling to genuine, clinically used physiological models.
Practice Tip: Before simulating the full two-variable glucose-insulin model, sketch by hand how you’d expect glucose and insulin to each rise and fall after a meal, reasoning about their interaction qualitatively first — then compare your sketch against the simulated curves to check your intuition against the model’s actual coupled behavior.
Common Mistake: Updating one of the two coupled state variables (say, glucose) using the OTHER variable’s already-updated new value within the same time step, instead of its value from the start of that step — when two state variables are coupled, both updates for a given time step must use each other’s CURRENT (pre-update) values consistently, or the simulation introduces an ordering-dependent bug that doesn’t reflect the model’s actual intended dynamics.
Important Questions:
- Q1: What two state variables does this chapter’s minimal model track together, and how are they coupled? Blood glucose concentration and blood insulin concentration. They are coupled because glucose’s rate of change depends on the current insulin level (insulin helps remove glucose from the bloodstream), while insulin’s rate of change depends on the current glucose level (glucose stimulates the release of more insulin).
- Q2: What extra care does simulating two coupled state variables together require, compared to the single-variable models from earlier chapters? Both variables’ next values must be computed using each other’s CURRENT (pre-update) values at that time step consistently, rather than one variable accidentally using the other’s already-updated new value — otherwise the simulation introduces an ordering bug that doesn’t correctly reflect the model’s intended coupled dynamics.
Chapter 19: Case Studies Part 2
Difficulty: Advanced · Modeling and Simulation — Week 10–11 · Key topics: Applying epidemiological and physiological modeling tools to new case studies, open-ended review exercises
This chapter closes out the book’s second part (epidemiology and physiology) with open-ended case studies that ask readers to apply the compartmental- and rate-based modeling tools from Chapters 11–18 — SIR-style compartments, vaccination, parameter sweeps, nondimensionalization, cooling and pharmacokinetic-style rate models, and coupled two-variable systems — to new problems on their own.
Key Points:
- Like the first case-studies chapter (Chapter 10), this chapter is a review-and-application checkpoint rather than an introduction of new techniques, this time covering the epidemiological and physiological modeling tools from Chapters 11 through 18.
- The case studies here draw on compartmental modeling (SIR and vaccination), parameter sweeps applied to rate-based systems, nondimensionalization, and coupled two-variable systems like the glucose-insulin model, requiring readers to judge which combination of tools fits each new problem.
- As with Chapter 10, these case studies are deliberately less structured than the step-by-step chapters that introduced each technique, testing whether the reader can select and apply the right tool for a new, only partially specified physiological or epidemiological question.
- This chapter marks another structural transition point in the book, closing the epidemiology-and-physiology material before the final several chapters shift the book’s focus to mechanics and motion (falling objects, projectiles, and rotation).
- The modeling discipline emphasized throughout this section — explicit assumptions, comparison against real clinical or epidemiological data, and evaluating a model by its usefulness — carries forward unchanged into the mechanics chapters that follow.
Memory Tip: Treat this chapter the same way as Chapter 10: work through its case studies actively before checking any solution, since the goal here is practicing which-tool-fits-which-problem judgment, not confirming a memorized procedure.
Common Mistake: Approaching this chapter’s case studies by trying to recall one single “correct” technique for each problem, rather than recognizing that several of the tools from Chapters 11–18 (compartments, sweeps, nondimensionalization, coupled variables) might reasonably apply, sometimes even in combination — open-ended modeling problems often don’t have one uniquely correct approach.
Important Questions:
- Q1: What range of modeling tools does this chapter’s case studies draw on? Tools from Chapters 11 through 18: SIR-style compartmental modeling, vaccination and herd immunity, parameter sweeps applied to rate-based systems, nondimensionalization, and coupled two-variable systems like the glucose-insulin minimal model.
- Q2: What structural role does this chapter play in the book, similar to Chapter 10’s role for Part 1? It serves as a review-and-application checkpoint closing out Part 2 of the book (epidemiology and physiology) before the final chapters shift the book’s focus to mechanics and motion.
Chapter 20: The Empire State Building Strikes Back
Difficulty: Advanced · Modeling and Simulation — Week 11 · Key topics: Falling object simulation, gravity, a first mechanics model without air resistance
This chapter opens the book’s final part on mechanics with a classic physics scenario: simulating an object falling from a height (playfully framed around the Empire State Building) under gravity alone, without air resistance. It implements Newton’s second law as a state-based simulation tracking position and velocity together, establishing the basic mechanics-simulation pattern extended in the following chapters.
Key Points:
- This chapter’s falling-object model tracks two coupled state variables — position and velocity — where velocity’s rate of change is determined by the constant acceleration due to gravity, and position’s rate of change is determined by the current velocity.
- Implementing this model directly applies Newton’s second law (force equals mass times acceleration) in its simplest form, since with no air resistance included, gravity is the only force acting on the falling object.
- This chapter deliberately starts WITHOUT air resistance, to first establish that position-velocity coupled simulation is a natural extension of the book’s existing state-update simulation pattern, before the next chapter adds the complexity of drag.
- Because there is no air resistance in this chapter’s version, the object’s simulated fall matches the classical closed-form physics equations for motion under constant acceleration, letting the simulation’s results be checked directly against the known analytical answer.
- This chapter’s position-velocity state pattern, established here for one-dimensional falling motion, is extended in the following chapters to two-dimensional projectile motion (Chapters 22–23) and rotational motion (Chapters 24–25).
Practice Tip: Before adding air resistance in the next chapter, verify this chapter’s no-air-resistance simulation against the classical closed-form equations for constant-acceleration motion by hand — confirming the simulation matches the known exact answer here builds confidence before drag makes an exact closed-form comparison much harder.
Common Mistake: Updating position using the OLD velocity from before that time step’s velocity update, rather than consistently deciding whether to use the velocity at the start or end of the step — this kind of subtle ordering choice in coupled position-velocity simulations can introduce small but compounding errors, and being deliberate and consistent about it matters for simulation accuracy.
Important Questions:
- Q1: What two coupled state variables does this chapter’s falling-object model track? Position and velocity: velocity’s rate of change is determined by the constant acceleration due to gravity, and position’s rate of change is determined by the object’s current velocity.
- Q2: Why does this chapter deliberately leave out air resistance, given that the next chapter adds it? To first establish the basic position-velocity coupled-state simulation pattern in its simplest form, where the result can be checked directly against the known classical closed-form physics equations for motion under constant acceleration, before the added complexity of air resistance makes an exact analytical comparison much harder.
Chapter 21: Drag
Difficulty: Advanced · Modeling and Simulation — Week 11–12 · Key topics: Air resistance, drag force proportional to velocity squared, terminal velocity
This chapter adds air resistance (drag) to the falling-object model from the previous chapter, modeling drag force as proportional to the square of the object’s velocity and opposing its direction of motion. It shows how including drag changes the falling object’s behavior qualitatively, introducing the concept of terminal velocity — the speed at which drag force exactly balances gravity, so the object stops accelerating.
Key Points:
- Drag force in this chapter’s model is proportional to the square of the object’s current velocity, and always acts in the direction opposing motion — growing rapidly as an object speeds up, unlike gravity, which stays constant.
- With drag included, the net force on a falling object is gravity minus the drag force, which itself depends on velocity, so the object’s acceleration is no longer constant as it was in the previous chapter’s simpler model.
- Terminal velocity is the speed at which the (velocity-dependent) drag force exactly equals the constant gravitational force, resulting in zero net force and therefore zero acceleration — once an object reaches terminal velocity, it continues falling at that same constant speed.
- Because drag depends on velocity squared, the resulting equations of motion generally cannot be solved with simple closed-form algebra the way the no-drag model in the previous chapter could, making numerical simulation a genuinely necessary tool rather than just a convenient alternative to an exact formula.
- This chapter’s drag model is the physical foundation for the more realistic falling and projectile-motion scenarios explored in the following baseball chapters, where drag significantly affects a ball’s real trajectory compared to a no-drag, purely gravitational prediction.
Memory Tip: Remember drag’s key distinguishing property compared to gravity: gravity is a constant force regardless of speed, while drag force grows with the SQUARE of velocity — this is exactly why a falling object’s acceleration decreases as it speeds up, eventually reaching zero acceleration at terminal velocity.
Common Mistake: Assuming a falling object keeps accelerating faster and faster forever, the way the no-drag model from the previous chapter predicted — once drag is included, the object’s acceleration actually decreases as its speed increases, eventually reaching zero acceleration at terminal velocity rather than continuing to speed up without limit.
Important Questions:
- Q1: How is drag force modeled in this chapter, and how does it relate to the object’s velocity? Drag force is modeled as proportional to the square of the object’s current velocity, and it always acts in the direction opposing the object’s motion — so drag grows rapidly as the object speeds up, unlike the constant force of gravity.
- Q2: What is terminal velocity, and why does an object stop accelerating once it reaches it? Terminal velocity is the speed at which the velocity-dependent drag force exactly equals the constant gravitational force, producing zero net force on the object. With zero net force, the object’s acceleration becomes zero, so it continues falling at that same constant terminal speed rather than continuing to speed up.
Chapter 22: Baseball
Difficulty: Advanced · Modeling and Simulation — Week 12 · Key topics: Two-dimensional projectile motion, simulating a hit baseball’s trajectory with drag, range and hang time
This chapter extends the one-dimensional drag model from the previous chapter to full two-dimensional projectile motion, simulating a hit baseball’s complete trajectory — both horizontal distance and vertical height over time — under gravity and drag together. It shows how splitting motion into horizontal and vertical components, each with its own coupled position-velocity state, lets the same simulation techniques from earlier chapters model a genuinely two-dimensional physical scenario.
Key Points:
- Two-dimensional projectile motion is modeled by tracking four coupled state variables together: horizontal position, vertical position, horizontal velocity, and vertical velocity, each updated according to the forces acting on the ball in that direction.
- Gravity acts only in the vertical direction (constantly pulling the ball downward), while drag acts in the direction opposing the ball’s current overall velocity vector, meaning it affects both the horizontal and vertical components of motion simultaneously.
- This chapter’s baseball model builds directly on the one-dimensional drag model from Chapter 21, extending the same physical drag-force equation to two dimensions rather than introducing a fundamentally new physical concept.
- The simulated trajectory can be used to compute practically meaningful outcomes like the ball’s total horizontal range (how far it travels before landing) and hang time (how long it stays in the air), given a chosen initial launch speed and angle.
- This chapter’s two-dimensional trajectory model sets up the next chapter’s optimization question — finding the launch angle that maximizes the ball’s range — by providing the underlying simulation needed to evaluate any given launch angle’s resulting distance.
Practice Tip: Before including drag, first simulate the baseball’s trajectory under gravity alone (reusing the no-drag pattern from Chapter 20, extended to two dimensions) and compare it against the classical parabolic trajectory formula — confirming the no-drag case matches known physics first makes it easier to trust the more complex drag-included version.
Common Mistake: Applying the drag force only to the ball’s vertical velocity component, forgetting that drag acts opposite to the ball’s actual overall velocity direction, not just its vertical motion — since a batted ball moves both horizontally and vertically at once, drag genuinely affects BOTH velocity components, and computing it correctly requires using the ball’s combined velocity magnitude and direction, not just one axis in isolation.
Important Questions:
- Q1: What four state variables does this chapter’s two-dimensional baseball trajectory model track together? Horizontal position, vertical position, horizontal velocity, and vertical velocity, all updated together at each time step according to the forces (gravity and drag) acting on the ball.
- Q2: How does drag’s effect on the ball’s motion differ from gravity’s effect, in this chapter’s two-dimensional model? Gravity acts only in the vertical direction, constantly pulling the ball downward, while drag acts in the direction opposing the ball’s current overall velocity vector — meaning drag affects both the horizontal and vertical components of the ball’s motion simultaneously, not just one axis.
Chapter 23: Optimal Baseball
Difficulty: Advanced · Modeling and Simulation — Week 12–13 · Key topics: Finding the optimal launch angle for maximum range, using optimization together with simulation, sweeping launch angle
This chapter uses the two-dimensional baseball trajectory model from the previous chapter to answer an optimization question: what launch angle maximizes a hit ball’s range, given drag? It sweeps the launch angle across a range of values, simulating the resulting trajectory and range for each one, and shows how the optimal angle with drag included differs from the classical 45-degree answer that holds only in the idealized no-drag case.
Key Points:
- This chapter treats launch angle as the swept parameter (reusing the parameter-sweep technique from Chapter 4), running the full two-dimensional trajectory simulation from the previous chapter once for each candidate launch angle and recording the resulting range.
- In the classical, idealized no-drag case, the launch angle that maximizes range is exactly 45 degrees — a well-known result from basic physics that this chapter uses as a baseline comparison.
- With realistic drag included, the optimal launch angle for maximum range is noticeably LESS than 45 degrees, because a higher launch angle keeps the ball in the air (and therefore exposed to drag’s slowing effect) longer, reducing the benefit of extra height compared to the no-drag case.
- Finding this drag-adjusted optimal angle requires simulation rather than a simple closed-form formula, since (as noted in Chapter 21) drag’s velocity-squared dependence generally rules out an exact algebraic solution — this chapter is a concrete example of using simulation specifically to solve an optimization problem.
- This chapter’s optimization-via-sweep-and-simulation approach — try many candidate values, simulate each one’s outcome, and find the best result — is a general problem-solving pattern applicable well beyond baseball, whenever a system’s exact optimal input cannot be found with closed-form calculus alone.
Memory Tip: Remember the key contrast with classical physics: the textbook “optimal angle is 45 degrees” result assumes no air resistance; once realistic drag is included, as in this chapter, the actual optimal launch angle for maximum range is measurably lower than 45 degrees.
Common Mistake: Assuming the classical 45-degree optimal launch angle still applies once air resistance (drag) is included in the model — that 45-degree result is specific to the idealized no-drag case from basic physics; this chapter’s simulation shows the drag-included optimal angle is noticeably lower, because drag penalizes the longer hang time that a higher launch angle produces.
Important Questions:
- Q1: What is the classical, no-drag optimal launch angle for maximizing a projectile’s range, and how does this chapter’s drag-included result compare to it? The classical no-drag optimal launch angle is exactly 45 degrees. With realistic drag included, this chapter’s simulation finds the optimal launch angle for maximum range is noticeably LESS than 45 degrees, because a higher angle keeps the ball airborne (and subject to drag) longer.
- Q2: Why does finding the drag-included optimal launch angle require simulation rather than a simple formula? Because drag force depends on the square of velocity, the resulting equations of motion generally cannot be solved with an exact closed-form algebraic formula (as noted in Chapter 21), so the optimal angle must instead be found by simulating the trajectory for many candidate launch angles and comparing their resulting ranges.
Chapter 24: Rotation
Difficulty: Advanced · Modeling and Simulation — Week 13 · Key topics: Rotational motion, angular position and angular velocity, moment of inertia
This chapter shifts the book’s mechanics material from linear (straight-line and projectile) motion to rotational motion, introducing angular position and angular velocity as the rotational analogues of the position and velocity used in earlier chapters, along with moment of inertia as the rotational analogue of mass. It sets up the state-based simulation pattern for rotating systems, extended in the next chapter with torque.
Key Points:
- Angular position (rotation angle) and angular velocity (rate of rotation) play the same structural role for rotational motion that position and velocity played for the linear motion modeled in Chapters 20–23, forming another pair of coupled state variables.
- Moment of inertia is introduced as the rotational analogue of mass: just as mass measures an object’s resistance to linear acceleration under a force, moment of inertia measures an object’s resistance to angular acceleration under a torque.
- Unlike mass, moment of inertia depends not just on an object’s total mass but on how that mass is distributed relative to the axis of rotation — mass concentrated farther from the axis contributes more to the moment of inertia than the same mass concentrated close to the axis.
- This chapter establishes the angular-position/angular-velocity coupled-state simulation pattern using the same loop-plus-update-function structure from earlier chapters, directly paralleling the linear-motion pattern from Chapter 20.
- This chapter deliberately introduces rotational kinematics (angular position and velocity) before rotational dynamics (the forces, in this case torque, that cause angular acceleration), which is covered in the following chapter.
Practice Tip: For each rotational concept in this chapter, explicitly write down its linear-motion counterpart from earlier chapters (angular position ↔ position, angular velocity ↔ velocity, moment of inertia ↔ mass) — building this parallel table makes the rotational material much easier to absorb by leaning on intuition already built for linear motion.
Common Mistake: Assuming moment of inertia is just another name for an object’s mass — moment of inertia depends not only on how much mass an object has, but critically on how that mass is distributed relative to the rotation axis; the same total mass arranged differently (closer to or farther from the axis) produces a different moment of inertia and therefore different rotational behavior.
Important Questions:
- Q1: What two state variables does this chapter introduce for rotational motion, and what are their linear-motion counterparts? Angular position (rotation angle) and angular velocity (rate of rotation), which play the same structural role for rotational motion that position and velocity played for the linear motion modeled in the earlier mechanics chapters.
- Q2: How does moment of inertia differ from ordinary mass, as this chapter explains it? Moment of inertia is the rotational analogue of mass, measuring resistance to angular acceleration under a torque, but unlike mass alone, it also depends on how an object’s mass is distributed relative to the axis of rotation — mass farther from the axis contributes more to the moment of inertia than the same mass located close to the axis.
Chapter 25: Torque
Difficulty: Advanced · Modeling and Simulation — Week 13–14 · Key topics: Torque as the rotational analogue of force, simulating a rotating system driven by torque, angular acceleration
This chapter completes the rotational-motion material begun in the previous chapter by introducing torque — the rotational analogue of force — and simulating a system whose angular velocity changes in response to an applied torque, divided by its moment of inertia. It closes the parallel between linear and rotational dynamics established across Chapters 20–25, applying it to a concrete rotating physical system.
Key Points:
- Torque is the rotational analogue of force: just as force causes linear acceleration (with mass resisting that acceleration), torque causes angular acceleration, with moment of inertia (introduced in the previous chapter) resisting that angular acceleration.
- The rotational version of Newton’s second law used in this chapter’s model is angular acceleration equals torque divided by moment of inertia — directly paralleling the linear version (acceleration equals force divided by mass) used in the earlier falling-object and baseball chapters.
- Simulating a torque-driven rotating system reuses the same coupled angular-position/angular-velocity state pattern established in the previous chapter, now with angular velocity’s rate of change driven by the applied torque rather than left constant or undefined.
- This chapter’s torque-driven simulation completes the deliberate structural parallel the book has built across the mechanics chapters: force/mass/linear-acceleration (Chapters 20–23) mirrored by torque/moment-of-inertia/angular-acceleration (Chapters 24–25).
- The rotational modeling techniques from this chapter and the previous one are applied together in the next chapter’s case studies, closing out the book’s final content part before the concluding “Under the Hood” chapter.
Memory Tip: Remember the rotational version of Newton’s second law by direct analogy: linear acceleration equals force divided by mass; angular acceleration equals torque divided by moment of inertia — the same relationship, with each linear quantity swapped for its rotational counterpart.
Common Mistake: Applying a torque value directly as if it were an angular acceleration, skipping the division by moment of inertia — just as a force by itself is not the same as the resulting linear acceleration (which also depends on mass), a torque by itself is not the same as the resulting angular acceleration, which depends on both the torque applied and the object’s moment of inertia.
Important Questions:
- Q1: What is torque, as introduced in this chapter, and what is its rotational role? Torque is the rotational analogue of force: it is what causes angular acceleration in a rotating system, the way force causes linear acceleration in the earlier mechanics chapters.
- Q2: What is the rotational version of Newton’s second law used in this chapter’s simulation, and what is its linear counterpart? Angular acceleration equals torque divided by moment of inertia. Its linear counterpart, used in the earlier falling-object and baseball chapters, is that linear acceleration equals force divided by mass — the same fundamental relationship, expressed in rotational terms.
Chapter 26: Case Studies Part 3
Difficulty: Advanced · Modeling and Simulation — Week 14 · Key topics: Applying mechanics modeling tools to new case studies, open-ended review exercises covering motion and rotation
This chapter closes out the book’s third and final content part (mechanics) with open-ended case studies that ask readers to apply the linear and rotational motion modeling tools from Chapters 20–25 — falling objects, drag, two-dimensional projectile motion, optimization via simulation, and rotational dynamics with torque — to new physical scenarios on their own.
Key Points:
- Like Chapters 10 and 19 before it, this chapter is a review-and-application checkpoint covering the mechanics tools from Chapters 20 through 25, rather than introducing new modeling techniques of its own.
- The case studies here draw on both linear mechanics (falling objects, drag, two-dimensional projectile trajectories, launch-angle optimization) and rotational mechanics (angular motion, moment of inertia, torque), asking readers to combine or choose between these tools as each new problem requires.
- As with the two earlier case-studies chapters, these exercises are deliberately more open-ended than the step-by-step chapters that introduced each individual technique, testing the reader’s ability to select and apply the right combination of tools for a new physical scenario.
- This chapter completes the book’s third and final content part, closing out the sequence of population growth (Part 1), epidemiology and physiology (Part 2), and mechanics (Part 3) modeling material.
- This chapter sets up the book’s concluding chapter, “Under the Hood,” which shifts from applying the modsim library to explaining how the library itself is implemented underneath the modeling tools used throughout the book.
Practice Tip: As with the earlier case-studies chapters, work through this chapter’s exercises actively before consulting any solution — and specifically notice which problems call for linear-motion tools, which call for rotational tools, and which might reasonably combine both.
Common Mistake: Treating the mechanics case studies in this chapter as purely a physics exercise disconnected from the book’s broader modeling philosophy — the same core modeling discipline emphasized throughout the book (explicit assumptions, real-data comparison, judging a model by its usefulness) applies just as much to these mechanics case studies as it did to the population and epidemiology case studies earlier in the book.
Important Questions:
- Q1: What range of modeling tools does this chapter’s case studies draw on? Tools from Chapters 20 through 25: linear mechanics (falling objects, drag, two-dimensional projectile motion, launch-angle optimization) and rotational mechanics (angular motion, moment of inertia, torque).
- Q2: What does this chapter set up for the book’s final chapter? It closes out the book’s third and final content part (mechanics), setting up the concluding chapter, “Under the Hood,” which shifts from applying the modsim library’s tools to explaining how the library itself is implemented underneath those tools.
Chapter 27: Under the Hood
Difficulty: Advanced · Modeling and Simulation — Week 14–15 · Key topics: How the modsim library is implemented, numerical integration methods, the connection between the book’s simple loops and real ODE solvers
This concluding chapter looks “under the hood” of the modsim library used throughout the book, explaining how its simulation functions are actually implemented in terms of numerical integration methods (like those provided by SciPy) and how the simple loop-based state-update pattern used in every earlier chapter relates to more formal, general-purpose ordinary differential equation solvers.
Key Points:
- This chapter reveals that the modsim library’s simulation functions, used as a fairly simple black box throughout the earlier chapters, are actually implemented using established numerical integration methods (via SciPy) under the hood, rather than some bespoke, book-specific technique.
- The book’s simple loop-based state-update pattern, used consistently since Chapter 3, is explained here as itself a basic form of numerical integration (specifically resembling the Euler method), connecting the book’s hands-on approach to the more general, formal theory of ODE solvers.
- This chapter discusses how more sophisticated numerical integration methods (beyond the simple step-by-step Euler-style approach used pedagogically throughout the book) can improve accuracy or efficiency for more demanding simulation problems.
- Understanding what happens “under the hood” equips a reader to move beyond the modsim library’s teaching-oriented interface toward using general-purpose scientific computing tools (like SciPy’s own ODE solvers) directly for more advanced modeling work.
- This chapter serves as a deliberate capstone: rather than introducing a wholly new application domain, it reflects back on the actual computational machinery underlying every simulation technique used across all three of the book’s content parts (growth, epidemiology/physiology, and mechanics).
Memory Tip: Remember this chapter’s core reveal in one line: the simple step-by-step loop used since Chapter 3 is itself a basic numerical integration method (resembling Euler’s method), and the modsim library’s convenience functions are really just a friendlier interface wrapped around established SciPy numerical solvers.
Common Mistake: Assuming the modsim library’s simulation functions use some unique, book-specific algorithm found nowhere else — this chapter reveals that the library is actually built on standard, established numerical integration methods from SciPy, and the book’s own simple update-loop pattern is itself recognizable as a basic (Euler-style) numerical integration technique, not an invented one-off method.
Important Questions:
- Q1: What does this concluding chapter reveal about how the modsim library’s simulation functions actually work? That they are implemented using established numerical integration methods from SciPy, rather than some bespoke, book-specific technique — the library is a friendlier, teaching-oriented interface wrapped around these general-purpose scientific computing tools.
- Q2: How does this chapter connect the book’s simple, loop-based state-update pattern (used since Chapter 3) to formal numerical integration theory? It explains that the simple step-by-step update loop used consistently throughout the book is itself a basic form of numerical integration, closely resembling the Euler method, linking the book’s hands-on, code-first approach to the more general, formal theory of ODE solvers.
Read Modeling and Simulation in Python Online (Free)
This book is free from its official source — author Allen B. Downey publishes it under a Creative Commons licence. There is no official free PDF — the print/ebook edition is sold separately by No Starch Press, so the legitimate free way to read this book is the complete, official web edition below, with every chapter fully readable online at no cost, alongside the accompanying Jupyter notebooks.
→ Read OnlineHow to Study This Book
This book is organized in three parts, each ending with an open-ended “Case Studies” review chapter: Chapters 1–10 build the core simulation toolkit using population growth as the running example, Chapters 11–19 apply it to epidemiology and physiology, and Chapters 20–27 apply it to mechanics and motion.
Chapters 1–4 (Modeling through Sweeping Parameters) establish the book’s fundamental state-based-simulation pattern — state variables, iteration, and parameter sweeps — and should be read in order before anything else, since every later chapter reuses this same pattern.
Each of the three “Case Studies” chapters (10, 19, 26) is a review-and-application checkpoint, not a source of new techniques — work through these actively before moving on, since they test whether the preceding chapters’ tools have actually been internalized.
The final chapter, “Under the Hood,” is best read last: it explains how the modsim library’s functions are actually implemented using SciPy’s numerical integration methods, which is easiest to appreciate after having used those functions throughout the rest of the book.
This book teaches by running code in Jupyter notebooks using the author’s own modsim Python library — working through the accompanying notebooks on the official site alongside the text is essential to how the material is meant to be used, and no prior programming experience is assumed.
Used In These Programs
This book is used as a Modeling and Simulation, Computational Science, or Python-based science elective text in: BSCS and Programming coursework. Browse all Computer Science category books.
Who Should Read This
Modeling and Simulation in Python is written for students and self-learners with little or no prior programming experience who want to learn how to build computational models of real systems — population growth, epidemics, physiology, and mechanics — using Python. It suits BSCS and engineering students taking a Modeling and Simulation or Computational Science elective, and is especially useful for anyone who wants to learn simulation and numerical methods through concrete, real-world case studies rather than abstract theory alone.
Applicable Universities
This book is useful for students at Pakistani universities offering BSCS or Engineering programs with a Modeling and Simulation, Computational Science, or Python-based science elective course, including Punjab University, Virtual University, COMSATS, FAST, UET, NUST, GIKI, and other HEC-recognized institutions, and for self-learners who want a free, beginner-friendly introduction to computational modeling.
FAQs
Is Modeling and Simulation in Python free?
Yes. The complete edition is free from its official source, published by the author, Allen B. Downey, under a Creative Commons licence, as a complete, browsable HTML edition with accompanying Jupyter notebooks.
Is there a free PDF of this book?
No official free PDF is published — the print and ebook editions are sold separately by No Starch Press. The legitimate free way to read this book is the complete official HTML edition, which contains every chapter in full.
Do I need prior programming experience before reading this book?
No. The book is explicitly designed for people who have not programmed before, and it teaches Python programming and modeling techniques together, side by side, using the author’s own modsim library.
What topics does this book cover?
Three main areas, each explored through simulation: population growth models (constant, logistic, and quadratic growth), epidemiology and physiology models (the SIR epidemic model, vaccination, pharmacokinetics, glucose-insulin dynamics), and mechanics (falling objects, drag, projectile motion, and rotational motion).
What is the modsim library used throughout this book?
It is the author’s own Python library, used throughout the book to simplify writing state-based simulations. The book’s final chapter, “Under the Hood,” explains that the library is actually built on established SciPy numerical integration methods.
What are the “Case Studies” chapters in this book?
Chapters 10, 19, and 26 are open-ended review chapters that close out each of the book’s three main parts (population growth, epidemiology/physiology, and mechanics), asking readers to apply the preceding chapters’ tools to new problems on their own.
Related Books
- Think Python – Allen B. Downey (the introductory Python foundation this book builds on)
- Think Stats – Allen B. Downey (a companion book applying Python to statistics)
- Think Complexity – Allen B. Downey (a companion book applying Python to complexity science and simulation)
Modeling and Simulation in Python is a free, beginner-friendly introduction to computational modeling — population growth, epidemics, physiology, and mechanics — taught by building working Python simulations of real systems and comparing them against real data. Browse more Computer Science books for the rest of your semester.
Modeling and Simulation in Python, by Allen B. Downey. Free under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 licence. Access for free at https://greenteapress.com/wp/modsimpy/
© Copyright Policy
Freebooks.pk is an educational resource for students in Pakistan. Textbooks and other books belong to their respective boards, authors and publishers, and all rights remain with them. If you are the copyright holder of any material on this page and want it changed or removed, please contact us or file a request under our DMCA policy. We review every request and remove reported content promptly.