0% found this document useful (0 votes)
21 views81 pages

Modeling and Simulation in Python Allen B Downey Instant Download

The document is a reference for 'Modeling and Simulation in Python' by Allen B. Downey, detailing its contents, including chapters on modeling, simulation, analysis, and specific applications like pharmacokinetics and thermal systems. It provides links to various versions and related works, as well as information about the author's licensing and permissions. The book is designed to teach modeling and simulation concepts using Python programming.

Uploaded by

rkrmivdn5741
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views81 pages

Modeling and Simulation in Python Allen B Downey Instant Download

The document is a reference for 'Modeling and Simulation in Python' by Allen B. Downey, detailing its contents, including chapters on modeling, simulation, analysis, and specific applications like pharmacokinetics and thermal systems. It provides links to various versions and related works, as well as information about the author's licensing and permissions. The book is designed to teach modeling and simulation concepts using Python programming.

Uploaded by

rkrmivdn5741
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Modeling And Simulation In Python Allen B Downey

download

https://ebookbell.com/product/modeling-and-simulation-in-python-
allen-b-downey-6855158

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Modeling And Simulation In Python Converted Allen B Downey

https://ebookbell.com/product/modeling-and-simulation-in-python-
converted-allen-b-downey-49550968

Modeling And Simulation In Python Jason M Kinser

https://ebookbell.com/product/modeling-and-simulation-in-python-jason-
m-kinser-42344096

Modeling And Simulation In Python An Introduction For Scientists And


Engineers Allen B Downey

https://ebookbell.com/product/modeling-and-simulation-in-python-an-
introduction-for-scientists-and-engineers-allen-b-downey-48274994

Modeling And Simulation In Python Allen B Downey

https://ebookbell.com/product/modeling-and-simulation-in-python-allen-
b-downey-52556530
Modeling And Simulation In Python Version 23 Allen B Downey

https://ebookbell.com/product/modeling-and-simulation-in-python-
version-23-allen-b-downey-7236520

Modeling And Simulation In Python Allen B Downey

https://ebookbell.com/product/modeling-and-simulation-in-python-allen-
b-downey-59378552

Simulation With Python Develop Simulation And Modeling In Natural


Sciences Engineering And Social Sciences 1st Edition Rongpeng Li

https://ebookbell.com/product/simulation-with-python-develop-
simulation-and-modeling-in-natural-sciences-engineering-and-social-
sciences-1st-edition-rongpeng-li-44887188

Handson Simulation Modeling With Python Develop Simulation Models For


Improved Efficiency And Precision In The Decisionmaking Process 2nd
Edition 2nd Edition Giuseppe Ciaburro

https://ebookbell.com/product/handson-simulation-modeling-with-python-
develop-simulation-models-for-improved-efficiency-and-precision-in-
the-decisionmaking-process-2nd-edition-2nd-edition-giuseppe-
ciaburro-48708554

Modeling And Simulation In Thermal And Fluids Engineering Krishnan


Murugesan

https://ebookbell.com/product/modeling-and-simulation-in-thermal-and-
fluids-engineering-krishnan-murugesan-48800954
Modeling and Simulation in Python

Version 1.0.2
Modeling and Simulation in Python

Version 1.0.2

Allen B. Downey

Green Tea Press


Needham, Massachusetts
Copyright © 2017 Allen B. Downey.

Green Tea Press


9 Washburn Ave
Needham MA 02492

Permission is granted to copy, distribute, transmit and adapt this work under a
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
License: http://modsimpy.com/license.

If you are interested in distributing a commercial version of this work, please


contact the author.

The LATEX source and code for this book is available from

https://github.com/AllenDowney/ModSimPy
iv
Contents

Preface xi
0.1 Can modeling be taught? . . . . . . . . . . . . . . . . . . . . xiii
0.2 How much programming do I need? . . . . . . . . . . . . . . xiv
0.3 How much math and science do I need? . . . . . . . . . . . . xv
0.4 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . xvi
0.5 Installing Python and the libraries . . . . . . . . . . . . . . . xvi
0.6 Copying my files . . . . . . . . . . . . . . . . . . . . . . . . . xvii
0.7 Running Jupyter . . . . . . . . . . . . . . . . . . . . . . . . xviii

1 Modeling 1
1.1 The falling penny myth . . . . . . . . . . . . . . . . . . . . . 1
1.2 Computation . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Modeling a bike share system . . . . . . . . . . . . . . . . . 4
1.4 Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Defining functions . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7 Print statements . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.8 If statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.9 Optional parameters . . . . . . . . . . . . . . . . . . . . . . 14
1.10 For loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
vi CONTENTS

1.11 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2 Simulation 17
2.1 Iterative modeling . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2 More than one System object . . . . . . . . . . . . . . . . . 18
2.3 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4 Negative bikes . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.5 Comparison operators . . . . . . . . . . . . . . . . . . . . . . 23
2.6 Metrics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.7 Functions that return values . . . . . . . . . . . . . . . . . . 26
2.8 Two kinds of parameters . . . . . . . . . . . . . . . . . . . . 27
2.9 Loops and arrays . . . . . . . . . . . . . . . . . . . . . . . . 28
2.10 Sweeping parameters . . . . . . . . . . . . . . . . . . . . . . 29
2.11 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

3 Explanation 31
3.1 World population data . . . . . . . . . . . . . . . . . . . . . 31
3.2 Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3 Constant growth model . . . . . . . . . . . . . . . . . . . . . 34
3.4 Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.5 Now with System objects . . . . . . . . . . . . . . . . . . . . 38
3.6 Proportional growth model . . . . . . . . . . . . . . . . . . . 39
3.7 Factoring out the update function . . . . . . . . . . . . . . . 41
3.8 Combining birth and death . . . . . . . . . . . . . . . . . . . 42
3.9 Quadratic growth . . . . . . . . . . . . . . . . . . . . . . . . 43
3.10 Equilibrium . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.11 Disfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
CONTENTS vii

4 Prediction 51
4.1 Generating projections . . . . . . . . . . . . . . . . . . . . . 51
4.2 Comparing projections . . . . . . . . . . . . . . . . . . . . . 54
4.3 Recurrence relations . . . . . . . . . . . . . . . . . . . . . . 55
4.4 Differential equations . . . . . . . . . . . . . . . . . . . . . . 57
4.5 Analysis and simulation . . . . . . . . . . . . . . . . . . . . 59
4.6 Analysis with WolframAlpha . . . . . . . . . . . . . . . . . . 60
4.7 Analysis with SymPy . . . . . . . . . . . . . . . . . . . . . . 61
4.8 Differential equations in SymPy . . . . . . . . . . . . . . . . 62
4.9 Solving the quadratic growth model . . . . . . . . . . . . . . 63
4.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

5 Design 65
5.1 The Freshman Plague . . . . . . . . . . . . . . . . . . . . . . 65
5.2 The SIR model . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.3 The SIR equations . . . . . . . . . . . . . . . . . . . . . . . 67
5.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.5 The update function . . . . . . . . . . . . . . . . . . . . . . 69
5.6 Running the simulation . . . . . . . . . . . . . . . . . . . . . 71
5.7 Collecting the results . . . . . . . . . . . . . . . . . . . . . . 71
5.8 Now with a TimeFrame . . . . . . . . . . . . . . . . . . . . . 73
5.9 Metrics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.10 Immunization . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.11 Hand washing . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.12 Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . 82

6 Analysis 85
viii CONTENTS

6.1 Unpack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.2 Sweeping beta . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.3 Sweeping gamma . . . . . . . . . . . . . . . . . . . . . . . . 88
6.4 Nondimensionalization . . . . . . . . . . . . . . . . . . . . . 90
6.5 Contact number . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.6 Analysis and simulation . . . . . . . . . . . . . . . . . . . . 94

7 Thermal systems 97
7.1 The coffee cooling problem . . . . . . . . . . . . . . . . . . . 97
7.2 Temperature and heat . . . . . . . . . . . . . . . . . . . . . 98
7.3 Heat transfer . . . . . . . . . . . . . . . . . . . . . . . . . . 99
7.4 Newton’s law of cooling . . . . . . . . . . . . . . . . . . . . . 100
7.5 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.6 Using fsolve . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
7.7 Mixing liquids . . . . . . . . . . . . . . . . . . . . . . . . . . 106
7.8 Mix first or last? . . . . . . . . . . . . . . . . . . . . . . . . 107
7.9 Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . 108
7.10 Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

8 Pharmacokinetics 113
8.1 The glucose-insulin system . . . . . . . . . . . . . . . . . . . 113
8.2 The glucose minimal model . . . . . . . . . . . . . . . . . . . 114
8.3 Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.4 Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.5 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 119
8.6 Numerical solution of differential equations . . . . . . . . . . 122
8.7 Least squares . . . . . . . . . . . . . . . . . . . . . . . . . . 124
CONTENTS ix

8.8 Interpreting parameters . . . . . . . . . . . . . . . . . . . . . 126


8.9 The insulin minimal model . . . . . . . . . . . . . . . . . . . 129

9 Projectiles 131
9.1 Newton’s second law of motion . . . . . . . . . . . . . . . . . 131
9.2 Dropping pennies . . . . . . . . . . . . . . . . . . . . . . . . 133
9.3 Onto the sidewalk . . . . . . . . . . . . . . . . . . . . . . . . 136
9.4 With air resistance . . . . . . . . . . . . . . . . . . . . . . . 137
9.5 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.6 Dropping quarters . . . . . . . . . . . . . . . . . . . . . . . . 140

10 Two dimensions 145


10.1 The Manny Ramirez problem . . . . . . . . . . . . . . . . . 145
10.2 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
10.3 Modeling baseball flight . . . . . . . . . . . . . . . . . . . . . 149
10.4 Trajectories . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
10.5 Finding the range . . . . . . . . . . . . . . . . . . . . . . . . 154
10.6 Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . 156
10.7 Finishing off the problem . . . . . . . . . . . . . . . . . . . . 158

11 Rotation 159
11.1 The physics of toilet paper . . . . . . . . . . . . . . . . . . . 160
11.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 161
11.3 Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
11.4 Torque . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
11.5 Moment of inertia . . . . . . . . . . . . . . . . . . . . . . . . 167
11.6 Unrolling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
11.7 Simulating a yo-yo . . . . . . . . . . . . . . . . . . . . . . . 173

Index 177
x CONTENTS
P
reface

Thi
sbooki
sabou
tm od
el
ingands
imula
tionofph
ysi
calsy
stem
s. Th
efo
llow
ing
di
agramshow
swh a
tI me
anb y“mod
el
in g
”:

Pr
l

Ana
lys
is
Mode

edi
ct
S
imu
lat
ion

i
on
ion

Val
ct

idat
stra

ion
Ab
tem

Dat
ys

a
S

Mea
suremen
t

St
artinginthelowe
rl e
ft
,thesystemissometh
inginth
erea
lwor
ldweare
int
erestedin
.O f
ten,i
tissome
thingcomp
li
cated
,sowehavet
ode
cidewh
ich
de
tai
l scanbesimpl
ifiedorabs
tractedaway
.

There
sultofabst
r a
cti
onisamode l thatinc
lud
esthefeatu
resweth
inkare
es
sent
ial
.Am odelcanberepr
esen
tedintheformofdi
agramsandequa
tion
s,
wh
ichcanb eusedform a
themat
ica
lana lys
is.Itcanal
sob eimp
lemen
tedin
thef
ormo facompu terpro
gram,whi
chc anruns
imulations.

Th
ere
sul
tofan
aly
sisands
imu
lat
ionc
anb
ea p
red
ict
ionabou
t wh
atth
e
xii Chapter 0 Preface

system will do, an explanation of why it behaves the way it does, or a design
intended to achieve a purpose.

We can validate predictions and test designs by taking measurements from


the real world and comparing the data we get with the results from analysis
and simulation.

This process is almost always iterative: for any physical system, there are
many possible models, each one including and excluding different features, or
including different levels of detail. The goal of the modeling process is to find
the model best suited to its purpose (prediction, explanation, or design).

Sometimes the best model is the most detailed. If we include more features,
the model is more realistic, and we expect its predictions to be more accurate.

But often a simpler model is better. If we include only the essential features
and leave out the rest, we get models that are easier to work with, and the
explanations they provide can be clearer and more compelling.

As an example, suppose someone asked you why the orbit of the Earth is nearly
elliptical. If you model the Earth and Sun as point masses (ignoring their
actual size), compute the gravitational force between them using Newton’s
law of universal gravitation, and compute the resulting orbit using Newton’s
laws of motion, you can show that the result is an ellipse.

Of course, the actual orbit of Earth is not a perfect ellipse, because of the
gravitational forces of the Moon, Jupiter, and other objects in the solar system,
and because Newton’s laws of motion are only approximately true (they don’t
take into account relativistic effects).

But adding these features to the model would not improve the explanation;
more detail would only be a distraction from the fundamental cause. However,
if the goal is to predict the position of the Earth with great precision, including
more details might be necessary.

So choosing the best model depends on what the model is for. It is usually a
good idea to start with a simple model, even if it is likely to be too simple,
and test whether it is good enough for its purpose. Then you can add features
gradually, starting with the ones you expect to be most essential.
0.1 Can modeling be taught? xiii

Comparing the results of successive models provides a form of internal vali-


dation, so you can catch conceptual, mathematical, and software errors. And
by adding and removing features, you can tell which ones have the biggest
effect on the results, and which can be ignored.

0.1 Can modeling be taught?

These essential modeling skills — abstraction, analysis, simulation, and vali-


dation — are central in engineering, natural sciences, social sciences, medicine,
and many other fields. Some students learn these skills implicitly, but in most
schools they are not taught explicitly, and students get little practice. That’s
the problem this book is meant to address.

At Olin College, we use this book in a class called Modeling and Simulation,
which all students take in their first semester. My colleagues, John Geddes
and Mark Somerville, and I developed this class and taught it for the first time
in 2009.

It is based on our belief that modeling should be taught explicitly, early, and
throughout the curriculum. It is also based on our conviction that computation
is an essential part of this process.

If students are limited to the mathematical analysis they can do by hand, they
are restricted to a small number of simple physical systems, like a projectile
moving in a vacuum or a block on a frictionless plane.

And they will only work with bad models; that is, models that are too simple
for their purpose. In nearly every mechanical system, air resistance and friction
are essential features; if we ignore them, our predictions will be wrong and our
designs won’t work.

In most freshman physics classes, students don’t make modeling decisions;


sometimes they are not even aware of the decisions that have been made for
them. Our goal is to teach, and for students to practice, the entire modeling
process.
xiv Chapter 0 Preface

0.2 How much programming do I need?


If you have never programmed before, you should be able to read this book,
understand it, and do the exercises. I will do my best to explain everything you
need to know; in particular, I have chosen carefully the vocabulary I introduce,
and I try to define each term the first time it it used. If you find that I have
used a term without defining it, let me know.

If you have programmed before, you will have an easier time getting started,
but you might be uncomfortable in some places. I take an approach to pro-
gramming you have probably not seen before.

Most programming classes1 have two big problems:

1. They go “bottom up”, starting with basic language features and gradu-
ally adding more powerful tools. As a result, it takes a long time before
students can do anything more interesting than convert Fahrenheit to
Celsius.

2. They have no context. Students learn to program with no particular goal


in mind, so the exercises span an incoherent collection of topics, and the
projects tend to be unmotivated.

In this book, you learn to program with an immediate goal in mind: writing
simulations of physical systems. And we proceed “top down”, by which I mean
we use professional-strength data structures and language features right away.
In particular, we use the following Python libraries:

ˆ NumPy for basic numerical computation (see http://www.numpy.org/).

ˆ SciPy for scientific computation (see http://www.scipy.org/).

ˆ matplotlib for visualization (see http://matplotlib.org/).

ˆ pandas for working with data (see http://pandas.pydata.org/).

ˆ SymPy for symbolic computation, (see http://www.sympy.org).

ˆ Pint for units like kilograms and meters (see http://pint.readthedocs.


io).
1
Including many I have taught.
0.3 How much math and science do I need? xv

ˆ Jupyter for reading, running, and developing code (see http://jupyter.


org).

These tools let you work on more interesting programs sooner, but there are
some drawbacks: they can be hard to use, and it can be challenging to keep
track of which library does what and how they interact.

I have tried to mitigate these problems by providing a library, called modsim,


that makes it easier to get started with these tools, and provides some addi-
tional capabilities.

Some features in the modsim library are like training wheels; at some point you
will probably stop using them and start working with the underlying libraries
directly. Other features you might find useful the whole time you are working
through the book, or even later.

I encourage you to read the the modsim library code. Most of it is not com-
plicated, and I tried to make it readable. Particularly if you have some pro-
gramming experience, you might learn something by reverse-engineering my
designs.

0.3 How much math and science do I need?


I assume that you have studied calculus. You should know what derivatives
and integrals are, but that’s about all. In particular, you don’t need to know
(or remember) much about finding derivatives or integrals of functions analyt-
ically. If you know the derivative of x2 and you can integrate 2x dx, that will
do it2 .

More importantly you should understand what those concepts mean; but if
you don’t, this book might help you figure it out.

You don’t have to know anything about differential equations.

As for science, we will cover topics from a variety of fields, including demogra-
phy, epidemiology, medicine, thermodynamics, and mechanics. For the most
part, I don’t assume you know anything about these topics. In fact, one of the
2
And if you noticed that those two questions answer each other, even better.
xvi Chapter 0 Preface

skills you need to do modeling is the ability to learn enough about new fields
to develop models and simulations.

When we get to mechanics, I assume you understand the relationship between


position, velocity, and acceleration, and that you are familiar with Newton’s
laws of motion, especially the second law, which is often expressed as F = ma
(force equals mass times acceleration).

I think that’s everything you need, but if you find that I left something out,
please let me know.

0.4 Getting started


To run the examples and work on the exercises in this book, you will need to
be able to:

1. Install Python on your computer, along with the libraries we will use.

2. Copy my files onto your computer.

3. Run Jupyter, which is a tool for running and writing programs, and load
a notebook, which is a file that contains code and text.

The next three sections provide details for these steps. I wish there were an
easier way to get started; it’s regrettable that you have to do so much work
before you write your first program. Be persistent!

0.5 Installing Python and the libraries


You might already have Python installed on your computer, but you might
not have the latest version. To use the code in this book, you need Python
3.6, or later. Even if you have the latest version, you probably don’t have all
of the libraries we need.

You could update Python and install these libraries, but I strongly recom-
mend that you don’t go down that road. I think you will find it easier to use
0.6 Copying my files xvii

Anaconda, which is a free Python distribution that includes all the libraries
you need for this book (and lots more).

Anaconda is available for Linux, macOS, and Windows. By default, it puts all
files in your home directory, so you don’t need administrator (root) permission
to install it, and if you have a version of Python already, Anaconda will not
remove or modify it.

[Detailed instructions coming soon.]

0.6 Copying my files


The code for this book is available from https://github.com/AllenDowney/
ModSimPy, which is a Git repository. Git is a software tool that helps you
keep track of the programs and other files that make up a project. A collection
of files under Git’s control is called a repository3 . GitHub is a hosting service
that provides storage for Git repositories and a convenient web interface.

There are several ways you can copy the files from my repository to your
computer.

If you don’t want to use Git at all, you can download my files in a Zip archive
from http://modsimpy.com/zip. Then you need a program like WinZip or
gzip to unpack the Zip file.

To use Git, you need a Git client, which is a program that manages git repos-
itories. If you have not used Git before, I recommend GitHub Desktop, which
is a simple graphical Git client. You can download it from https://desktop.
github.com. Currently, GitHub Desktop is not available for Linux. On Linux,
I suggest using the Git command-line client. Installation instructions are at
http://modsimpy.com/git.

Once you have a Git client, you can use it to copy files from my repository to
your computer, which is called cloning in Git’s vocabulary. If you are using
a Command-line git client, type

git clone https://github.com/AllenDowney/ModSimPy


3
The really cool kids call it a “repo”.
xviii Chapter 0 Preface

You don’t need a GitHub account to do this, but you won’t be able to write
your changes back to GitHub.

If you want to use GitHub to keep track of the code you write while you are
using this book, you can make of a copy of my repository on GitHub, which
is called forking. If you don’t already have a GitHub account, you’ll need to
create one.

Use a browser to view the homepage of my repository at https://github.


com/AllenDowney/ModSimPy. You should see a gray button in the upper right
that says Fork. If you press it, GitHub will create a copy of my repository that
belongs to you. Then you can clone your repository like this:

git clone https://github.com/YourGitHubUserName/ModSimPy

Of course, you should replace YourGitHubUserName with your GitHub user


name.

0.7 Running Jupyter


The code for each chapter, and starter code for the exercises, is in Jupyter
notebooks. If you have not used Jupyter before, you can read about it at
http://jupyter.org.

[Jupyter instructions coming soon.]

Contributor List
If you have a suggestion or correction, send it to [email protected].
Or if you are a Git use, send me a pull request!

If I make a change based on your feedback, I will add you to the contributor
list, unless you ask to be omitted.

If you include at least part of the sentence the error appears in, that makes it
easy for me to search. Page and section numbers are fine, too, but not as easy
to work with. Thanks!
0.7 Running Jupyter xix

ˆ I am grateful to John Geddes and Mark Somerville for their early col-
laboration with me to create Modeling at Simulation, the class at Olin
College this book is based on.

ˆ My early work on this book benefited from conversations with my amaz-


ing colleagues at Olin College, including John Geddes, Alison Wood,
Chris Lee, and Jason Woodard.

ˆ I am grateful to Lisa Downey and Jason Woodard for their thoughtful


and careful copy editing.
xx Chapter 0 Preface
Chapter 1

Modeling

The world is a complicated place. In order to make sense of it, we use models,
which are generally smaller and simpler than the thing we want to study. The
word “model” means different things in different contexts, so it is hard to
define except by example.

Some models are actual objects, like a scale model of a car, which has the
same shape as the car, but smaller. Scale models are often useful for testing
properties of mechanical systems, like air resistance.

This book is about mathematical models, which are ideas, not objects. If
you studied Newton’s laws of motion, what you learned is a mathematical
model of how objects move in space when forces are applied to them.

1.1 The falling penny myth


Let’s see an example of how models are used. You might have heard that a
penny dropped from the top of the Empire State Building would be going so
fast when it hit the pavement that it would be embedded in the concrete; or
if it hit a person, it would break their skull.

We can test this myth by making and analyzing a model. To get started, I’ll
assume that the effect of air resistance is small. This will turn out to be a bad
assumption, but bear with me. If air resistance is negligible, the primary force
2 Chapter 1 Modeling

acting on the penny is gravity, which causes the penny to accelerate downward.

If the initial velocity is 0, the velocity after t seconds is at, and the height the
penny has dropped at t is
h = at2 /2
Using algebra, we can solve for t:
p
t= 2h/a

Plugging in the acceleration of gravity, a = 9.8 m/s2 and the height of the
Empire State Building, h = 381 m, we get t = 8.8 s. Then computing v = at
we get a velocity on impact of 86 m/s, which is about 190 miles per hour. That
sounds like it could hurt.

Of course, these results are not exact because the model is based on simplifi-
cations. For example, we assume that gravity is constant. In fact, the force
of gravity is different on different parts of the globe, and gets weaker as you
move away from the surface. But these differences are small, so ignoring them
is probably a good choice for this scenario.

On the other hand, ignoring air resistance is not a good choice. Once the penny
gets to about 18 m/s, the upward force of air resistance equals the downward
force of gravity, so the penny stops accelerating. After that, it doesn’t matter
how far the penny falls; it hits the sidewalk (or your head) at about 18 m/s,
much less than 86 m/s, as the simple model predicts.

The statistician George Box famously said “All models are wrong, but some
are useful.” He was talking about statistical models, but his wise words apply
to all kinds of models. Our first model, which ignores air resistance, is very
wrong, and probably not useful. The second model is also wrong, but much
better, and probably good enough to refute the myth.

The television show Mythbusters has tested the myth of the falling penny more
carefully; you can view the results at http://modsimpy.com/myth. Their work
is based on a mathematical model of motion, measurements to determine the
force of air resistance on a penny, and a physical model of a human head.
1.2 Computation 3

1.2 Computation
There are (at least) two ways to work with mathematical models, analysis
and simulation. Analysis often involves algebra and other kinds of symbolic
manipulation. Simulation often involves computers.

In this book we do some analysis and a lot of simulation; along the way, I
discuss the pros and cons of each. The primary tools we use for simulation are
the Python programming language and Jupyter, which is an environment for
writing and running programs.

As a first example, I’ll show you how I computed the results from the previous
section using Python. You can view this example, and the other code in this
chapter, at http://modsimpy.com/chap01. For instructions for downloading
and running the code, see Section 0.4.

First I’ll create a variable to represent acceleration.

a = 9.8 * meter / second**2

A variable is a name that corresponds to a value. In this example, the name is


a and the value is the number 9.8 multiplied by the units meter / second**2.
This example demonstrates some of the symbols Python uses to perform math-
ematical operations:

Operation Symbol
Addition +
Subtraction -
Multiplication *
Division /
Exponentiation **

Next, we can compute the time it takes for the penny to drop 381 m, the height
of the Empire State Building.

h = 381 * meter
t = sqrt(2 * h / a)
4 Chapter 1 Modeling

These lines create two more variables: h gets the height of the building in
meters; t gets the time, in seconds, for the penny to fall to the sidewalk. sqrt
is a function that computes square roots. Python keeps track of units, so the
result, t, has the correct units, seconds.

Finally, we can compute the velocity of the penny after t seconds:

v = a * t

The result is about 86 m/s, again with the correct units.

This example demonstrates analysis and computation using Python. Next


we’ll see an example of simulation.

1.3 Modeling a bike share system


Imagine a bike share system for students traveling between Olin College and
Wellesley College, which are about 3 miles apart in eastern Massachusetts.

This example demonstrates the features of Python we’ll use to develop com-
putational simulations of real-world systems. Along the way, I will make deci-
sions about how to model the system. In the next chapter we’ll review these
decisions.

Suppose the system contains 12 bikes and two bike racks, one at Olin and one
at Wellesley, each with the capacity to hold 12 bikes.

As students arrive, check out a bike, and ride to the other campus, the number
of bikes in each location changes. In the simulation, we’ll need to keep track of
where the bikes are. To do that, I’ll create a System object, which is defined
in the modsim library.

Before we can use the library, we have to import it:

from modsim import *

This line of code is an import statement that tells Python to read the file
modsim.py and make the functions it defines available.
1.3 Modeling a bike share system 5

Functions in the modsim.py library include sqrt, which we used in the previous
section, and System, which we are using now. System creates a System object,
which is a collection of system variables.

bikeshare = System(olin=10, wellesley=2)

In this example, the system variables are olin and wellesley and they repre-
sent the number of bikes at Olin and Wellesley. The initial values are 10 and
2, indicating that there are 10 bikes at Olin and 2 at Wellesley. The System
object created by System is assigned to a new variable named bikeshare.

We can read the variables inside a System object using the dot operator,
like this:

bikeshare.olin

The result is the value 10. Similarly, for:

bikeshare.wellesley

The result is 2. If you forget what variables a system object has, you can just
type the name:

bikeshare

The result looks like a table with the variable names and their values:

value
olin 10
wellesley 2

The system variables and their values make up the state of the system. We
can update the state by assigning new values to the variables. For example,
if a student moves a bike from Olin to Wellesley, we can figure out the new
values and assign them:

bikeshare.olin = 9
bikeshare.wellesley = 3
6 Chapter 1 Modeling

Or we can use update operators, -= and += to subtract 1 from olin and


add 1 to wellesley:

bikeshare.olin -= 1
bikeshare.wellesley += 1

The result is the same either way.

1.4 Plotting
As the state of the system changes, it is often useful to plot the values of the
variables over time. The modsim library provides a functions that creates a
new figure:

newfig()

In Jupyter, the behavior of this function depends on a command in the first


cell:

ˆ If you want the figures to appear in the notebook, use


%matplotlib notebook

ˆ If you want the figures to appear in separate windows, use


%matplotlib qt

These commands are not actually Python; they are so-called “magic com-
mands” that control the behavior of Jupyter.

The following lines plot the state of the system:

plot(bikeshare.olin, 'rs-')
plot(bikeshare.wellesley, 'bo-')

The plot function takes two values, called arguments:


1.5 Defining functions 7

ˆ The first argument is the variable to plot. In this example, it’s a number,
but we’ll see later that plot can handle other objects, too.

ˆ The second argument is a “style string” that determines what the plot
should look like. In general, a string is a sequence of letters, numbers,
and punctuation that appear in quotation marks. The style string 'rs-'
means we want red squares with lines between them; 'bo-' means we
want blue circles with lines.

The plotting functions in the modsim library are based on Matplotlib, which is
a Python library for generating figures. To learn more about these functions,
you can read the Matplotlib documentation. For more about style strings, see
http://modsimpy.com/plot.

1.5 Defining functions


So far we have used functions defined in modsim and other libraries. Now we’re
going to define our own functions.

When you are developing code in Jupyter, it is often efficient to write 1–2 lines
in each cell, test them to confirm they do what you intend, and then use them
to define a new function. For example, these lines move a bike from Olin to
Wellesley:

bikeshare.olin -= 1
bikeshare.wellesley += 1

Rather than repeat them every time a bike moves, we can define a new func-
tion:

def bike_to_wellesley():
bikeshare.olin -= 1
bikeshare.wellesley += 1

def is a special word in Python that indicates we are defining a new function.
The name of the function is bike_to_wellesley. The empty parentheses indi-
cate that this function takes no arguments. The colon indicates the beginning
of an indented code block.
8 Chapter 1 Modeling

The next two lines are the body of the function. They have to be indented;
by convention, the indentation is 4 spaces.

When you define a function, it has no immediate effect. The body of the func-
tion doesn’t run until you call the function. Here’s how to call this function:

bike_to_wellesley()

When you call this function, it updates the variables of the bikeshare object;
you can check by displaying or plotting the new state.

When you call a function that takes no arguments, you have to include the
empty parentheses. If you leave them out, like this:

bike_to_wellesley

Python looks up the name of the function and displays:

<function __main__.bike_to_wellesley>

This result indicates that bike_to_wellesley is a function. You don’t have


to know what __main__ means, but if you see something like this, it probably
means that you looked up a function but you didn’t actually run it. So don’t
forget the parentheses.

1.6 Parameters
Similarly, we can define a function that moves a bike from Wellesley to Olin:

def bike_to_olin():
bikeshare.wellesley -= 1
bikeshare.olin += 1

And run it like this:

bike_to_olin()
1.6 Parameters 9

One benefit of defining functions is that you avoid repeating chunks of code,
which makes programs smaller. Another benefit is that the name you give the
function documents what it does, which makes programs more readable.

In this example, there is one other benefit that might be even more important.
Putting these lines in a function makes the program more reliable because it
guarantees that when we decrease the number of bikes at Olin, we increase
the number of bikes at Wellesley. That way, we guarantee that the bikes in
the model are neither created nor destroyed!

However, now we have two functions that are nearly identical except for a
change of sign. Repeated code makes programs harder to work with, because
if we make a change, we have to make it in several places.

We can avoid that by defining a more general function that moves any number
of bikes in either direction:

def move_bike(n):
bikeshare.olin -= n
bikeshare.wellesley += n

The name in parentheses, n, is a parameter of the function. When we run


the function, the argument we provide gets assigned to the parameter. So if
we run move_bike like this:

move_bike(1)

It assigns the value of the argument, 1, to the parameter, n, and then runs the
body of the function. So the effect is the same as:

n = 1
bikeshare.olin -= n
bikeshare.wellesley += n

Which moves a bike from Olin to Wellesley. Similarly, if we call move_bike


like this:

move_bike(-1)
10 Chapter 1 Modeling

The effect is the same as:

n = -1
bikeshare.olin -= n
bikeshare.wellesley += n

Which moves a bike from Wellesley to Olin. Now that we have move_bike, we
can rewrite the other two functions to use it:

def bike_to_wellesley():
move_bike(1)

def bike_to_olin():
move_bike(-1)

If you define the same function name more than once, the new definition
replaces the old one.

1.7 Print statements


As you write more complicated programs, it is easy to lose track of what is
going on. One of the most useful tools for debugging is the print statement,
which displays text in the Jupyter notebook.

Normally when Jupyter runs the code in a cell, it displays the value of the last
line of code. For example, if you run:

bikeshare.olin
bikeshare.wellesley

Jupyter runs both lines of code, but it only displays the value of the second
line.

If you want to display more than one value, you can use print statements:

print(bikeshare.olin)
print(bikeshare.wellesley)
1.8 If statements 11

print is a function, so it takes an argument in parentheses. It can also take a


sequence of arguments separated by commas, like this:

print(bikeshare.olin, bikeshare.wellesley)

In this example, the two values appear on the same line, separated by a space.

Print statements are also useful for debugging functions. For example, if you
add a print statement to move_bike, like this:

def move_bike(n):
print('Running move_bike with n =', n)
bikeshare.olin -= n
bikeshare.wellesley += n

The first argument of print is a string; the second is the value of n, which is
a number. Each time you run move_bike, it displays a message and the value
n.

1.8 If statements
The modsim library provides a function called flip that takes as an argument
a probability between 0 and 1:

flip(0.7)

The result is one of two values: True with probability 0.7 or False with
probability 0.3. If you run this function 100 times, you should to get True
about 70 times and False about 30 times. But the results are random, so
they might differ from these expectations.

True and False are special values defined by Python. Note that they are
not strings. There is a difference between True, which is a special value, and
'True', which is a string.

True and False are called boolean values because they are related to Boolean
algebra (http://modsimpy.com/boolean).
12 Chapter 1 Modeling

We can use boolean values to control the behavior of the program using an if
statement:

if flip(0.5):
print('heads')

If the result from flip is True, the program displays the string 'heads'.
Otherwise it does nothing.

The punctuation for if statements is similar to the punctuation for function


definitions: the first line has to end with a colon, and the lines inside the if
statement have to be indented.

Optionally, you can add an else clause to indicate what should happen if the
result is False:

if flip(0.5):
print('heads')
else:
print('tails')

Now we can use flip to simulate the arrival of students who want to borrow
a bike. Suppose we have data from previous observations about how many
students arrive at a particular time of day. If students arrive every 2 minutes,
on average, then during any one-minute period, there is a 50% chance a student
will arrive:

if flip(0.5):
bike_to_wellesley()

At the same time, there might be an equal probability that a student at


Wellesley wants to ride to Olin:

if flip(0.5):
bike_to_olin()

We can combine these snippets of code into a function that simulates a time
step, which is an interval of time, like one minute:
1.8 If statements 13

def step():
if flip(0.5):
bike_to_wellesley()

if flip(0.5):
bike_to_olin()

Then we can run a time step, and update the plot, like this:

step()
plot_state()

In reality, the probability of an arrival will vary over the course of a day, and
might be higher or lower, at any point in time, at Olin or Wellesley. So instead
of putting the constant value 0.5 in step we can replace it with a parameter,
like this:
def step(p1, p2):
if flip(p1):
bike_to_wellesley()

if flip(p2):
bike_to_olin()

Now when you call step, you have to provide two arguments:

step(0.4, 0.2)

The arguments you provide, 0.4 and 0.2, get assigned to the parameters, p1
and p2, in order. So running this function has the same effect as:

p1 = 0.4
p2 = 0.2

if flip(p1):
bike_to_wellesley()

if flip(p2):
bike_to_olin()
14 Chapter 1 Modeling

1.9 Optional parameters


When you add parameters to a function, you can provide default values, like
this:

def step(p1=0.5, p2=0.5):


if flip(p1):
bike_to_wellesley()

if flip(p2):
bike_to_olin()

Because they have default values, these parameters are optional; if you run
step with no arguments, and don’t forget the parentheses, like this:

step()

The parameters get the default values, so p1 and p2 are both 0.5. If you
provide one argument, like this:

step(0.4)

The value you provide overrides the default value of p1, but p2 still gets the
default. If you provide two arguments, it overrides both.

step(0.4, 0.2)

If you want to override p2 only, and accept the default for p1, you have to
provide the name of the parameter explicitly:

step(p2=0.2)

It is always legal to provide parameter names along with the arguments:

step(p1=0.4, p2=0.2)

Providing parameters names makes programs more readable and less error-
prone, because you don’t have to worry about the order of the arguments.
1.10 For loops 15

For example, if you reverse the order, it still assigns the right value to each
parameter:

step(p2=0.2, p1=0.4)

1.10 For loops


At some point you will get sick of running cells over and over. Fortunately,
there is an easy way to repeat a chunk of code, the for loop. Here’s an
example:

for i in range(4):
bike_to_wellesley()
plot_state()

The punctuation here should look familiar; the first line ends with a colon,
and the lines inside the for loop are indented. The other elements of the for
loop are:

ˆ The words for and in are special words we have to use in a for loop.

ˆ range is a Python function we’re using here to control the number of


times the loop runs.

ˆ i is a loop variable that gets created when the for loop runs. In this
example we don’t actually use i; we will see examples later where we
use the loop variable inside the loop.

When this loop runs, it runs the statements inside the loop four times, which
moves one bike at a time from Olin to Wellesley, and plots the updated state
of the system after each move.

1.11 Debugging
The goal of this chapter is to give you the minimal set of tools to get you
started. At this point, you know enough to write simple simulations of systems
16 Chapter 1 Modeling

like the Olin–Wellesley bikeshare. Along with each chapter, I provide a Jupyter
notebook that contains the code from the chapter, so you can run it, see how
it works, modify it, and see how it breaks.

When something goes wrong, Python provides error messages with information
about the problem. This information can help with debugging, but error
messages are often hard to understand.

When you are learning a programming language, it is a good idea to make as


many mistakes as you can, deliberately, so you can see what happens. You
will start to understand the error messages better, which helps when you make
errors accidentally.
Chapter 2

Simulation

To paraphrase two Georges, “All models are wrong, but some models are more
wrong than others.” In this chapter, I demonstrate the process we use to make
models less wrong.

As an example, we’ll review the bikeshare model from the previous chapter,
consider its strengths and weaknesses, and gradually improve it. We’ll also see
ways to use the model to understand the behavior of the system and evaluate
designed intended to make it work better.

You can view the code for this chapter at http://modsimpy.com/chap02. For
instructions for downloading and running the code, see Section 0.4.

2.1 Iterative modeling


The model we have so far is simple, but it is based on unrealistic assumptions.
Before you go on, take a minute to review the code from the previous chapter,
which you can view at http://modsimpy.com/chap01. This code represents
a model of the bikeshare system. What assumptions is it based on? Make a
list of ways this model might be unrealistic; that is, what are the differences
between the model and the real world?

Here are some of the differences on my list:


18 Chapter 2 Simulation

ˆ In the model, a student is equally likely to arrive during any one-minute


period. In reality, this probability varies depending on time of day, day
of the week, etc.

ˆ The model does not account for travel time from one bike station to
another.

ˆ The model does not check whether a bike is available, so it’s possible for
the number of bikes to be negative (as you might have noticed in some
of your simulations).

Some of these modeling decisions are better than others. For example, the first
assumption might be reasonable if we simulate the system for a short period
of time, like one hour.

The second assumption is not very realistic, but it might not affect the results
very much, depending on what we use the model for.

On the other hand, the third assumption seems problematic, and it is relatively
easy to fix. In Section 2.4, we will.

This process, starting with a simple model, identifying the most important
problems, and making gradual improvements, is called iterative modeling.

For any physical system, there are many possible models, based on different
assumptions and simplifications. It often takes several iterations to develop a
model that is good enough for the intended purpose, but no more complicated
than necessary.

2.2 More than one System object


Before we go on, I want to make a few changes to the code from the previous
chapter. First, I will generalize the functions we wrote so they take a System
object as a parameter. Then, we will make the code more readable by adding
documentation.

Here are two functions from the previous chapter, move_bike and plot_state:
2.2 More than one System object 19

def move_bike(n):
bikeshare.olin -= n
bikeshare.wellesley += n

def plot_state():
plot(bikeshare.olin, 'rs-', label='Olin')
plot(bikeshare.wellesley, 'bo-', label='Wellesley')

One problem with these functions is that they always use bikeshare, which
is a System object. As long as there is only one System object, that’s fine,
but these functions would be more flexible if they took a System object as a
parameter. Here’s what that looks like:

def move_bike(system, n):


system.olin -= n
system.wellesley += n

def plot_state(system):
plot(system.olin, 'rs-', label='Olin')
plot(system.wellesley, 'bo-', label='Wellesley')

The name of the parameter is system rather than bikeshare as a reminder


that the value of system could be any System object, not just bikeshare.

Now I can create as many System objects as I want:

bikeshare1 = System(olin=10, wellesley=2)


bikeshare2 = System(olin=2, wellesley=10)

And update them independently:

bike_to_olin(bikeshare1)
bike_to_wellesley(bikeshare2)

Changes in bikeshare1 do not affect bikeshare2, and vice versa. This be-
havior will be useful later in the chapter when we create a series of System
objects to simulate different scenarios.
20 Chapter 2 Simulation

2.3 Documentation
Another problem with the code we have so far is that it contains no documen-
tation. Documentation is text we add to programs to help other programmers
read and understand them. It has no effect on the program when it runs.

There are two forms of documentation, docstrings and comments. A doc-


string is a string in triple-quotes that appears at the beginning of a function,
like this:

def run_steps(system, num_steps=1, p1=0.5, p2=0.5):


"""Simulate the given number of time steps.

system: bikeshare System object


num_steps: number of time steps
p1: probability of an Olin->Wellesley customer arrival
p2: probability of a Wellesley->Olin customer arrival
"""
for i in range(num_steps):
step(system, p1, p2)
plot_state(system)

Docstrings follow a conventional format:

ˆ The first line is a single sentence that describes what the function does.

ˆ The following lines explain what each of the parameters are.

A function’s docstring should include the information someone needs to know


to use the function; it should not include details about how the function works.
That’s what comments are for.

A comment is a line of text that begins with a hash symbol, #. It usually


appears inside a function to explain something that would not be obvious to
someone reading the program.

For example, here is a version of move_bike with a docstring and a comment.


2.4 Negative bikes 21

def move_bike(system, n):


"""Move a bike.

system: bikeshare System object


n: +1 to move from Olin to Wellesley or
-1 to move from Wellesley to Olin
"""
# Because we decrease one system variable by n
# and increase the other by n, the total number
# of bikes is unchanged.
system.olin -= n
system.wellesley += n

At this point we have more documentation than code, which is not unusual
for short functions.

2.4 Negative bikes

The changes we’ve made so far improve the quality of the code, but we haven’t
done anything to improve the quality of the model yet. Let’s do that now.

Currently the code does not check whether a bike is available when a customer
arrives, so the number of bikes at a location can be negative. That’s not very
realistic. Here’s an updated version of move_bike that fixes the problem:
22 Chapter 2 Simulation

def move_bike(system, n):


# make sure the number of bikes won't go negative
olin_temp = system.olin - n
if olin_temp < 0:
return

wellesley_temp = system.wellesley + n
if wellesley_temp < 0:
return

# update the system


system.olin = olin_temp
system.wellesley = wellesley_temp

The comments explain the two sections of the function: the first checks to
make sure a bike is available; the second updates the state.

The first line creates a variable named olin_temp that gets the number of
bikes that would be at Olin if n bikes were moved. I added the suffix _temp to
the name to indicate that I am using it as a temporary variable.

move_bike uses the less-than operator, <, to compare olin_temp to 0. The


result of this operator is a boolean. If it’s True, that means olin_temp is
negative, which means that there are not enough bikes.

In that case I use a return statement, which causes the function to end
immediately, without running the rest of the statements. So if there are not
enough bikes at Olin, we “return” from move_bike without changing the state.
We do the same if there are not enough bikes at Wellesley.

If both of these tests pass, we run the last two lines, which assigns the values
from the temporary variables to the corresponding system variables.

Because olin_temp and wellesley_temp are created inside a function, they


are local variables, which means they only exist inside the function. At the
end of the function, they disappear, and you cannot read or write them from
anywhere else in the program.

In contrast, the system variables olin and wellesley belong to system, the
System object that was passed to this function as a parameter. When we
2.5 Comparison operators 23

change system variables inside a function, those changes are visible in other
parts of the program.

This version of move_bike makes sure we never have negative bikes at either
station. But what about bike_to_wellesley and bike_to_olin; do we have
to update them, too? Here they are:

def bike_to_wellesley(system):
move_bike(system, 1)

def bike_to_olin(system):
move_bike(system, -1)

Because these functions use move_bike, they take advantage of the new feature
automatically. We don’t have to update them.

2.5 Comparison operators


In the previous section, we used the less-than operator to compare two values.
For completeness, here are the other comparison operators:

Operation Symbol
Less than <
Greater than >
Less than or equal <=
Greater than or equal >=
Equal ==
Not equal !=

The equals operator, ==, compares two values and returns True if they are
equal and False otherwise. It is easy to confuse with the assignment op-
erator, =, which assigns a value to a variable. For example, the following
statement uses the assignment operator, which creates x if it doesn’t already
exist and gives it the value 5
24 Chapter 2 Simulation

x = 5

On the other hand, the following statement checks whether x is 5 and returns
True or False. It does not create x or change its value.

x == 5

You can use the equals operator in an if statement, like this:

if x == 5:
print('yes, x is 5')

If you make a mistake and use = in the first line of an if statement, like this:

if x = 5:
print('yes, x is 5')

That’s a syntax error, which means that the structure of the program is
invalid. Python will print an error message and the program won’t run.

2.6 Metrics
Getting back to the bike share system, at this point we have the ability to
simulate the behavior of the system. Since the arrival of customers is random,
the state of the system is different each time we run a simulation. Models like
this are called stochastic; models that do the same thing every time they run
are deterministic.

Suppose we want to use our model to predict how well the bike share system
will work, or to design a system that works better. First, we have to decide
what we mean by “how well” and “better”.

From the customer’s point of view, we might like to know the probability of
finding an available bike. From the system-owner’s point of view, we might
want to minimize the number of customers who don’t get a bike when they
want one, or maximize the number of bikes in use. Statistics like these that
are intended to quantify how well the system works are called metrics.
2.6 Metrics 25

As a simple example, let’s measure the number of unhappy customers. Here’s


a version of move_bike that keeps track of the number of customers who arrive
at a station with no bikes:

def move_bike(system, n):


olin_temp = system.olin - n
if olin_temp < 0:
system.olin_empty += 1
return

wellesley_temp = system.wellesley + n
if wellesley_temp < 0:
system.wellesley_empty += 1
return

system.olin = olin_temp
system.wellesley = wellesley_temp

Inside move_bike, we update the values of olin_empty, which is the number of


times a customer finds the Olin station empty, and wellesley_empty, which
is the number of unhappy customers at Wellesley.

That will only work if we initialize olin_empty and wellesley_empty when


we create the System object, like this:

bikeshare = System(olin=10, wellesley=2,


olin_empty=0, wellesley_empty=0)

Now we can run a simulation like this:

run_steps(bikeshare, 60, 0.4, 0.2)

And then check the metrics:

print(bikeshare.olin_empty, bikeshare.wellesley_empty)

Because the simulation is stochastic, the results are different each time it runs.
26 Chapter 2 Simulation

2.7 Functions that return values


We have used several functions that return values; for example, when you run
sqrt, it returns a number you can assign to a variable.

t = sqrt(2 * h / a)

When you run System, it returns a new System object:

bikeshare = System(olin=10, wellesley=2)

Not all functions have return values. For example, when you run plot, it adds
a point to the current graph, but it doesn’t return a value. The functions we
wrote so far are like plot; they have an effect, like changing the state of the
system, but they don’t return values.

To write functions that return values, we can use a second form of the return
statement, like this:

def add_five(x):
return x + 5

add_five takes a parameter, x, which could be any number. It computes


x + 5 and returns the result. So if we run it like this, the result is 8:

add_five(3)

As a more useful example, here’s a new function that creates a System object,
runs a simulation, and then returns the System object as a result:

def run_simulation():
system = System(olin=10, wellesley=2,
olin_empty=0, wellesley_empty=0)
run_steps(system, 60, 0.4, 0.2, plot=False)
return system

If we call run_simulation like this:


2.8 Two kinds of parameters 27

system = run_simulation()

It assigns to system a new System object, which we can use to check the
metrics we are interested in:

print(system.olin_empty, system.wellesley_empty)

2.8 Two kinds of parameters

This version of run_simulation always starts with the same initial condition,
10 bikes at Olin and 2 bikes at Wellesley, and the same values of p1, p2, and
num_steps. Taken together, these five values are the parameters of the
model, which are values that determine the behavior of the model.

It is easy to get the parameters of a model confused with the parameters


of a function. They are closely related ideas; in fact, it is common for the
parameters of the model to appear as parameters in functions. For example,
we can write a more general version of run_simulation that takes p1 and p2
as function parameters:

def run_simulation(p1=0.4, p2=0.2):


bikeshare = System(olin=10, wellesley=2,
olin_empty=0, wellesley_empty=0)
run_steps(bikeshare, 60, p1, p2, plot=False)
return bikeshare

Now we can run it with different arrival rates, like this:

system = run_simulation(p1=0.6, p2=0.3)

Then we can see how the metrics, like the number of unhappy customers,
depend on the parameters of the model. But before we do that, we need a
new version of a for loop.
28 Chapter 2 Simulation

2.9 Loops and arrays


In Section 1.10, we saw a loop like this:

for i in range(4):
bike_to_wellesley()
plot_state()

The loop variable, i, gets created when the loop runs, but it is not used for
anything. Now here’s a loop that actually uses the loop variable:

p1_array = linspace(start=0, stop=1, num=5)

for p1 in p1_array:
print(p1)

linspace is a function defined in the modsim library. It takes three arguments,


start, stop, and num. In this example, it creates a sequence of 5 equally-
spaced numbers, starting at 0 and ending at 1.
The result is a NumPy array, which is a new kind of object we have not seen
before. An array is a container for a sequence of numbers.
In the for loop, the values from the array are assigned to the loop variable one
a time. When this loop runs, it
1. Gets the first value from the array and assigns it to p1.
2. Runs the body of the loop, which prints p1.
3. Gets the next value from the array and assigns it to p1.
4. Runs the body of the loop, which prints p1.
And so on, until it gets to the end of the range. The result is:

0.0
0.25
0.5
0.75
1.0

This will come in handy in the next section.


Exploring the Variety of Random
Documents with Different Content
of all the faculty, yet the lads could do no less than go to his
assistance.
“Maybe he’s hurt,” said Tom.
“He’s too tough for that,” was the opinion of Bricktop.
Before the crowd of players reached the prostrate teacher he had
arisen. His face was first red and then pale by turns, so great was
his rage. He looked at the dirt on his clothes, and then at his book,
lying face downward some distance away.
“Young gentlemen!” he cried in his sternest voice. “Young
gentlemen, I object to this! Most emphatically do I object! You have
gone entirely too far! It is disgraceful! You shall hear further of this!
You may all report to me in half an hour in my room! I most
seriously object! It is disgraceful that such conduct should be
allowed at any college! I shall speak to Dr. Churchill and enter a
most strenuous objection! The idea!”
He replaced his glasses, which had fallen off, and accepted his
book that Tom picked up.
“Don’t forget,” he added severely. “I shall expect you all to report
to me in half an hour.”
At that moment Dr. Albertus Churchill, the aged and dignified head
of the college, and Mr. Andrew Zane, a proctor, came strolling along.
“Ah! I shall report your disgraceful conduct to Dr. Churchill at
once,” added Professor Tines, as he walked toward the venerable,
white-haired doctor. “I shall enter my strongest objection to the
continuance of football here.”
There were blank looks on the faces of the players.
CHAPTER VII
THE FIRST LINE-UP
Evidently Dr. Churchill surmised that something unusual had
occurred, for he changed his slow pace to a faster gait as he
approached the football squad, in front of which stood Professor
Tines, traces of anger still on his unpleasant face.
“Ah, young gentlemen, at football practice, I see,” remarked the
doctor, smiling. “I trust there is the prospect of a good team, Mr.
Lighton. I was very well pleased with the manner in which the
baseball nine acquitted itself, and I trust that at the more strenuous
sport the colors of Randall will not be trailed in the dust.”
“Not if I can help it, sir; nor the boys, either,” replied the coach.
“That’s right,” added Captain Holly Cross.
“I see you also take an interest in the sport,” went on Dr. Churchill
to Professor Tines. “I am glad the members of the faculty lend their
presence to sports. Nothing is so ennobling——”
“Sir,” cried Professor Tines, unable to contain himself any longer, “I
have been grossly insulted to-day. I wish to enter a most emphatic
protest against the continuance of football at this college. But a
moment ago, as I was crossing the field, reading this Greek volume,
I was knocked over by the ball. I now formally demand that football
be abolished.”
Dr. Churchill looked surprised.
“I want the guilty one punished,” went on Professor Tines. “Who
kicked that ball at me?”
“Yes, young gentlemen, who did it?” repeated the proctor, for he
thought it was time for him to take a hand. “I demand to know!”
“It wasn’t any one in particular, sir,” answered Coach Lighton,
determined to defend his lads. “It was done on a new play we were
trying, and it would be hard to say——”
“I think perhaps I had better investigate,” said Dr. Churchill.
“Young gentlemen, kindly report at my study in half an hour.”
“If you please, sir,” spoke Phil Clinton, “Professor Tines asked us to
call and see him.”
“Ah, I did not know that. Then I waive my right——”
“No, I waive mine,” interrupted the Latin teacher, and he
smoothed out some of the pages in the Greek book.
“Perhaps we had better have them all up to my office,” proposed
the proctor. “It is larger.”
“A good idea,” said the president of Randall. “Gentlemen, you may
report to the proctor in half an hour. I like to see the students
indulge in sports, but when it comes to such rough play that the life
of one of my teachers is endangered, it is time to call a halt.”
“His life wasn’t in any danger,” murmured Tom.
“Hush!” whispered the coach. “Leave it to me, and it will come out
all right.”
“But if they abolish football!” exclaimed Phil. “That will be too
much! We’ll revolt!”
“They’ll not abolish it. I’ll make some explanation.”
Dr. Churchill, Professor Tines, and the proctor moved away,
leaving a very disconsolate group of football candidates on the
gridiron.
“Do you suppose Pitchfork will prevail upon Moses to make us stop
the game?” asked Jerry Jackson. “Moses,” as has been explained,
being the students’ designation of Dr. Churchill.
“We’ll get up a counter protest to Pitchfork’s if they do,” added his
brother, Joe Jackson.
“Hurrah for the Jersey twins!” exclaimed Tom. The two brothers,
who looked so much alike that it was difficult to distinguish them,
were from the “Garden State,” and thus had gained their nickname.
“Well, that sure was an unlucky kick of mine,” came from Holly
Cross sorrowfully.
“Nonsense! You’re not to blame,” said Kindlings Woodhouse. “It
might have happened to any of us. We’ll all hang together.”
“Or else we’ll hang separately, as one of the gifted signers of the
Fourth of July proclamation put it,” added Ed Kerr. “Well, let’s go take
our medicine like little soldiers.”
In somewhat dubious silence they filed up to the proctor’s office.
It was an unusual sight to see the entire football squad thus in
parade, and scores of students came from their rooms to look on.
Dr. Churchill and Professor Tines were on hand to conduct the
investigation. The latter stated his case at some length, and
reiterated his demand that football be abolished. In support of his
contention he quoted statistics to show how dangerous the game
was, how many had been killed at it, and how often innocent
spectators, like himself, were sometimes hurt, though, he added, he
would never willingly be a witness of such a brutal sport.
“Well, young gentlemen, what have you to say for yourselves?”
asked Dr. Churchill, and Tom thought he could detect a twinkle in the
president’s eye.
Then Coach Lighton, who was a wise young man, began a
defense. He told what a fine game football was, how it brought out
all that was best in a lad, and how sorry the entire squad was that
any indignity had been put upon Professor Tines. He was held in
high esteem by all the students, Mr. Lighton said, which was true
enough, though esteem and regard are very different.
Finally the coach, without having hinted in the least who had
kicked the ball that knocked the professor down, offered, on behalf
of the team, to present a written apology, signed by every member
of the squad.
“I’m sure nothing can be more fair than that,” declared Dr.
Churchill. “I admit that I should be sorry to see football abolished
here, Professor Tines.”
Professor Tines had gained his point, however, and was satisfied.
He had made himself very important, and had, as he supposed,
vindicated his dignity. The apology was then and there drawn up by
the proctor, and signed by the students.
“I must ask for one stipulation,” said the still indignant instructor.
“I must insist that, hereafter, when I, or any other member of the
faculty approaches, all indiscriminate knocking or kicking of balls
cease until we have passed on. In this way all danger will be
avoided.”
“We agree to that,” said Mr. Lighton quickly, and the incident was
considered closed. But Professor Tines, if he had only known it, was
the most disliked instructor in college from then on. He had been
hated before, but now the venom was bitter against him.
“We’re well out of that,” remarked Tom to Phil, as they went to
their room, having gotten rid of their football togs. “I wonder what
fun Pitchfork has in life, anyhow?”
“Reading Latin and Greek, I guess. That reminds me, I must bone
away a bit myself to-night. I guess Sid is in,” he added, as he heard
some one moving about in the room.
They entered to find their chum standing on a chair, reaching up
to one of the silken banners Tom had hung with such pride.
“Here, you old anchorite! What are you doing?” cried Phil.
“Why, I’m trying to make this room look decent,” said Sid. “You’ve
got it so cluttered up that I can’t stand it! Isn’t it enough to have
pictures stuck all over?”
“Here, you let that banner alone!” cried Tom, and he gave such a
jerk to the chair on which Sid was standing that the objector to
things artistic toppled to the floor with a resounding crash.
“I’ll punch your head!” he cried to Tom, who promptly ensconced
himself behind the bed.
“Hurt yourself?” asked Phil innocently. “If you did it’s a judgment
on you, misogynist that you are.”
“You dry up!” growled Sid, as he rubbed his shins.
Then, peace having finally been restored, they all began studying,
while waiting for the summons to supper. When the bell rang, Phil
and Tom made a mad rush for the dining-room.
“Football practice gives you a fine appetite,” observed Phil.
“I didn’t know you fellows needed any inducement to make you
eat,” spoke Sid.
“Neither we do,” said Tom. “But come on, Phil, if he gets there
first there’ll be little left for us, in spite of his gentle words.”
“We’ll have harder work at practice to-morrow,” continued Phil as
they sat down at the table. “It will be the first real line-up, and I’m
anxious to see how I’ll do against Shipman.”
“He’s got Gerhart’s place for good, has he?” asked Tom.
“It looks so. Pass the butter, will you? Do you want it all?”
“Not in the least, bright-eyes. Here; have a prune.”
“Say, you fellows make me tired,” observed Sid.
“What’s the matter with you lately, old chap?” asked Tom. “You’re
as grumpy as a bear with a sore nose. Has your girl gone back on
you?”
“There you go again!” burst out Sid. “Always talking about girls! I
declare, since those pictures and things are up in the room, you two
have gone daffy! I’ll have ’em all down, first thing you know.”
“If you do, we’ll chuck you in the river,” promised Phil.
Thus, amid much good-natured banter, though to an outsider it
might not sound so, the supper went on. There was more hazing
that night, in which Phil and Tom had a share, but Sid would not
come out, saying he had to study.
“Come on, Tom,” called Phil the next afternoon, “all out for the
first real line-up of the season. I’m going to run the ’varsity against
the scrub, and I want to see how I make out.”
“Has the ’varsity eleven all been picked out?” asked Tom anxiously.
“Practically so, though, of course, there will be changes.”
“I wonder if I——”
“You’re to go at left-end. Come on, and we’ll get our togs on.”
After a little preliminary practice the two teams were told to line-
up for a short game of fifteen-minute halves. Coach Lighton named
those who were to constitute a provisional ’varsity eleven, and, to
his delight, Tom’s name was among the first named. Phil went to
quarter, naturally, and several of Tom’s chums found themselves
playing with him.
“Now try for quick, snappy work from the start,” was the advice of
the coach. “Play as though you meant something, not as if you were
going on a fishing trip, and it didn’t matter when you got there.”
The ball was put into play. The ’varsity had it, and under the
guidance of Phil Clinton, who gave his signals rapidly, the scrub was
fairly pushed up the field, and a little later the ’varsity had scored a
touchdown. Goal was kicked, and then the lads were ready for
another tussle.
The scrub, by dint of extraordinary hard work, managed to keep
the ball for a considerable time, making the necessary gains by
rushes.
“We must hold ’em, fellows!” pleaded Phil, and Captain Holly Cross
added his request to that end, in no uncertain words.
Shipman, the scrub quarter, passed the pigskin to his right half-
back, and the latter hit the line hard. Phil Clinton, seeing an opening,
dove in for a tackle. In some way there was a fumble, and Phil got
the ball. The next instant Jerry Jackson, who was on the ’varsity,
slipped and fell heavily on Phil’s right shoulder. The plucky quarter-
back stifled a groan that came to his lips, and then, turning over on
his back, stretched out white and still on the ground.
“Phil’s hurt!” cried Holly Cross. “Hold on, fellows!”
Tom bent over his chum. He felt of his shoulder.
“It’s dislocated,” he said. “We’d better get the doctor for him,
Holly.”
CHAPTER VIII
LANGRIDGE AND GERHART PLOT
“Some of you fellows run for Dr. Marshall!” called Mr. Lighton to
the throng that gathered about the prostrate lad.
“I’ll go,” volunteered Joe Jackson.
“No, let me,” said his twin brother. “It was my fault. I slipped and
fell on him.”
“It wasn’t any fellow’s fault in particular,” declared the captain. “It
was likely to happen to any one. But suppose you twins both go, and
then we’ll be sure to have help. If Dr. Marshall isn’t in the college,
telephone to Haddonfield for one. Phil’s shoulder must be snapped
back into place.”
As the twins started off Phil opened his eyes.
“Hurt much, old chap?” asked Tom, holding his chum’s hand.
“No—not—not much,” but Phil gritted his teeth as he said it. His
shoulder, with the bunch of padding on it, stood out oddly from the
rest of his body.
“Put some coats under him,” ordered the coach. “Shall we carry
you inside, Phil?”
“No; don’t move me. Is my arm broken?”
“No; only a dislocation, I guess. You’ll be all right in a few days.”
“Soon enough to play against Boxer Hall, I hope,” said Phil with a
faint smile.
“Of course,” declared the coach heartily. “We’ll delay the game if
necessary.”
“Here comes Dr. Marshall,” called Ed Kerr, as the college physician
was seen hurrying across the campus, with the Jersey twins trailing
along behind.
The doctor, after a brief examination, pronounced it a bad
dislocation, but then and there, with the help of the captain and
coach, he reduced it, though the pain, as the bone snapped into
place, made Phil sick and faint. Then they helped him to his room,
where he was soon visited by scores of students, for the quarter-
back was a general favorite.
“Now I think I will have to establish a quarantine,” declared Dr.
Marshall, when about fifty lads had been in to see how the patient
was progressing. “I don’t want you to get a fever from excitement,
Clinton. If you expect to get into the game again inside of two
weeks, you must keep quiet.”
“Two weeks!” cried Phil. “If I have to stay out as long as that I’ll
be so out of form that I’ll be no good.”
“Well, we’ll see how the ligaments get along,” was all the
satisfaction the doctor would give the sufferer.
Tom and Sid remained with their chum, and, after the physician
had left, they made all sorts of insane propositions to Phil with a
view of making him more comfortable.
“Shall I read Greek to you?” offered Sid. “Maybe it would take
your mind off your trouble.”
“Greek nothing,” replied Phil with a smile. “Haven’t I troubles
enough without that?”
“If I had some cheese I would make a Welsh rarebit,” Tom said. “I
used to be quite handy at it; not the stringy kind, either.”
“Get out, you old rounder!” exclaimed Sid. “Welsh rarebit would be
a fine thing for an invalid, wouldn’t it?”
“Well, maybe fried oysters would be better,” admitted Tom
dubiously. “I could smuggle some in the room, only the measly
things drip so, and Proc. Zane has been unusually active of late in
sending his scouts around.”
“I’ll tell you what you can do, if you want to,” spoke Phil.
“What’s that?” asked Tom eagerly.
“Send word to my sister, over at Fairview. She may hear
something about this, and imagine it’s worse than it is. I’d like her to
get it straight. I got a letter from dad to-day, too, saying mother was
a little better. I’d like sis to read it.”
“I’ll go myself, and start right away!” exclaimed Tom
enthusiastically. “I can get permission easily enough, for I’ve been
doing good work in class lately. I’ll come back on the midnight
trolley.”
“You’re awfully anxious to go, aren’t you?” asked Sid.
“Of course,” replied Tom. “Why do you speak so?”
“I believe Miss Madge Tyler attends at Fairview,” went on Sid to no
one in particular, and there was a mocking smile on his face.
“Oh, you just wait!” cried Tom, shaking his fist at his chum, who
sank down into the depths of the old easy chair, and held up his feet
as fenders to keep the indignant one at a distance. “You’ll get yours
good and proper some day.”
“Well, if you’re going, you’d better start,” said Phil. “I forgot,
though. You’ve never met my sister. That’s a go!”
“Can’t you give me a note to her?” asked Tom, who was fertile in
expedients where young ladies were concerned.
“I guess so. Lucky it’s my left instead of my right shoulder that’s
out of business. Give me some paper, Sid.”
“Tom doesn’t need a note,” was the opinion of the amateur
woman-hater. “He’ll see Miss Tyler, and she’ll introduce him.”
“That’s so,” agreed Tom, as if he had just thought of it. “That will
do first rate. Never mind the note, Phil,” and he hurried off, lest
something might occur that would prevent his visit.
He readily obtained permission to go to Fairview Institute, and
was soon hurrying along the river road to catch a trolley car. As he
crossed a bridge over the stream, he heard voices on the farther
end. It was dusk, now, and he could not see who the speakers were.
But he heard this conversation:
“Did you hear about Clinton?”
“Yes; he’s laid up with a bad shoulder. Well, it may be just the
chance we want.”
“That’s odd,” thought Tom. “I wonder who they can be? Evidently
college fellows. Yet how can Phil’s injury give them the chance they
want?”
He kept on, and a moment later came in sight of the speakers. He
saw that they were Fred Langridge and Garvey Gerhart.
“Good evening,” said Tom civily enough, for, though he and
Langridge were not on the best of terms, they still spoke.
“Off on a lark?” asked the former pitcher with a sneer. “I thought
you athletic chaps didn’t do any dissipating.”
“I’m not going to,” said Tom shortly, as he passed on.
“Do you suppose he heard what we said?” asked Gerhart, as the
shadows swallowed up Tom.
“No; but it doesn’t make much difference. He wouldn’t
understand. Now, do you think you can do it?”
“Of course. What I want to do is to keep him laid up for several
weeks. That will give me an opportunity of getting back on the
eleven. He was responsible for me being dropped, and now it’s my
turn.”
“But are you sure it will work?”
“Of course. I know just how to make the stuff. A fellow told me. If
we can substitute it for his regular liniment it will do the trick all
right.”
“That part will be easy enough. I can think up a scheme for that.
But will it do him any permanent harm? I shouldn’t want to get into
trouble.”
“No, it won’t harm him any. It will make him so he can’t use his
arm for a while, but that’s what we want. The effects will pass away
in about a month, just too late to let him get on the eleven.”
“All right; if you know what you’re doing, I’ll help. Now then,
where will we get the stuff?”
“I know all about that part. But let’s get off this bridge. It’s too
public. Come to a quieter place, where we can talk.”
“I know a good place. There’s a quiet little joint in town, where we
can get a glass of beer.”
“Will it be safe?”
“Sure. Come on,” and Langridge and his crony disappeared in the
darkness, talking, meanwhile, of a dastardly plot they had evolved to
disable Phil Clinton.
Tom kept on his way to the trolley.
“I wonder what Langridge and Gerhart meant?” he thought as he
quickened his pace on hearing an approaching car. “Perhaps Gerhart
thought he had a chance to get back on the team, because Phil is
laid up. But I don’t believe he has.”
But Tom’s interpretation of the words he had heard was far from
the truth. Phil Clinton was in grave danger.
CHAPTER IX
SOME GIRLS
Tom thought the fifteen-mile trolley ride to Fairview was an
unusually long one, but, as a matter of fact, it was soon
accomplished, for he caught an express, and about eight o’clock that
night arrived in the town where the co-educational institution was
located.
“Now to find Phil’s sister,” he said half aloud, as he headed for the
college. He knew the way well, for he had been there several times
before in the previous spring, when his team played baseball.
“Hello, Parsons,” a voice greeted him as he was walking up the
campus. “Where you bound for?”
The speaker was Frank Sullivan, manager of the Fairview ball
team.
“Oh, I just came over to see what sort of a football eleven you
were going to stack up against us this fall,” answered Tom easily.
“Not very good, I’m afraid,” declared Frank. “We’re in pretty bad
shape. Several of our best men have been hurt in practice.”
“We’ve got a few cripples ourselves,” said Tom. “Phil Clinton just
got laid up with a bad shoulder.”
“Our half-back is a wreck,” added Frank.
It is curious, but true, nevertheless, that most football elevens
seem to rejoice in the number of cripples they can boast of. The
worse the men are “banged up,” the better those interested in the
team seem to be. It may be that they wish to conceal from other
teams their real condition, and so give the enemy a false idea of
their strength. However that may be, the fact remains.
“So you came over to see how we were doing, eh?” went on
Frank. “Well, not very good, I’m afraid. We expect to be the
tailenders this season,” which was not at all what Frank expected,
however, nor did his friends. But he considered it policy to say so.
“I didn’t come over for that alone,” said Tom. “I have a message
to Phil’s sister. Say, how do you get into the female department of
this shebang, anyhow? What’s the proper method of procedure? Do
I have to have the password and a countersign?”
“Pretty nearly. It’s like the combination on a safe. The first thing
you will have to do is to go and interview Miss Philock.”
“Who’s she?”
“The preceptress; and a regular ogress into the bargain. If you
pass muster with her first inspection, you’ll have to answer a lot of
categorical questions covering your whole life history. Then, maybe,
she’ll consent to take a note from you to the fair damsel.”
“Can’t I see her?” asked Tom in some dismay, for he had counted
on meeting Madge Tyler.
“See a girl student of Fairview after dark? Why, the idea is
preposterous, my dear sir! Perfectly scandalous!” and Frank gave a
fair imitation of an indignant lady teacher.
“Well, I’ll have to send word in,” decided Tom, “for I didn’t bring a
note.”
“Do you know her personally?” asked Frank.
“Who—Miss Philock or Phil’s sister?”
“Phil’s sister?”
“No, I don’t.”
“Worse and more of it. I wish you joy of your job. But I’m off.
There’s going to be some hazing, and I’m on the committee to
provide some extra tortures for the freshies. So long. Miss Philock
has her den in that red building on your left,” and, whistling a merry
air, which was utterly out of keeping with Tom’s spirits, Frank
Sullivan walked away.
“Well, here goes,” said Tom to himself, as he walked up to the
residence of the preceptress and rang the bell.
An elderly servant answered his summons, and looked very much
surprised at observing a good-looking youth standing on the steps.
Tom asked to see Miss Philock, and the servant, after shutting the
door, and audibly locking it, walked away.
“They must be terribly afraid of me,” thought Tom, but further
musings were put to an end by the arrival of the preceptress herself.
“What do you want, young man?” she asked, and her voice
sounded like some file rasping and scraping.
“I wish to deliver a message to Miss Ruth Clinton,” was Tom’s
answer.
“Who are you?”
“I am Thomas Parsons, of Randall College.”
“Are you any relation to Miss Clinton?”
“No; but I room with her brother, and he was slightly hurt in
football practice to-day. He wanted me to tell her that it was nothing
serious. He also has a letter from his father, that he wished me to
deliver.”
Miss Philock fairly glared at Tom.
“That is a very ingenious and plausible answer,” said the elderly
lady slowly. “I have had many excuses made to me by young
gentlemen as reasons for sending messages to young ladies under
my care, but this one is the most ingenious I have ever received.”
“But it’s true!” insisted Tom, who perceived that his story was not
believed.
“That’s what they all say,” was the calm answer of Miss Philock.
Tom was nonplused. He hardly knew what reply to make.
“You are evidently a stranger to our rules,” went on Miss Philock.
“You must go away at once, or I shall notify the proctor,” and she
was about to close the door.
“But,” cried Tom desperately, “I have a message for Miss Ruth
Clinton!”
“Are you a relative of hers?” again asked the preceptress coldly.
“No; not exactly,” spoke Tom slowly.
“That’s the way they all say it,” she went on. “If you are not a
relative you can send her no message.”
“But can’t you tell her what I’ve told you?” asked the ’varsity
pitcher. “She may worry about her brother, and he wants her to have
this letter from her father.”
“How do I know she has a brother?” asked Miss Philock sternly.
“I am telling you.”
“Yes, I know,” frigidly. “Other young men have called here to see
the young ladies under my charge, and they often pretend to be
brothers and cousins, when they were not.”
“I am not pretending.”
“I don’t know whether you are or not, sir. It has been my
experience that you can never trust a young man. I shall have to bid
you good evening, though I do you the credit to state that your plan
is a very good one. Only, I am too sharp for you, young man. You
can send no message to Miss Clinton or any other young lady
student under my charge.”
The door was almost shut. Tom was in despair. At that moment he
caught sight of a girlish figure in the hall behind the preceptress. It
was Madge Tyler.
“Oh, Madge—Miss Tyler!” he cried impulsively, “will you tell Miss
Clinton that her brother is not badly hurt. That is, in case she hears
any rumors. His shoulder is dislocated, but he’s all right.”
“Why, Mr. Parsons—Tom!” exclaimed the girl in surprise. “What
brings you here?”
“Young man, what do you mean by disobeying my orders in this
manner?” demanded Miss Philock, bristling with anger.
“You didn’t tell me not to speak to Miss Tyler,” said Tom slyly. And
he smiled mischievously.
“Miss Tyler—do you know her?”
“I am an old friend of hers,” insisted Tom quickly, his confidence
coming back.
“Is this true, Miss Tyler?” asked the head instructress.
Madge was a bright girl, and a quick thinker. She at once
understood Tom’s predicament, and resolved to help him out.
Perhaps it was as much on her own account as Ruth’s—who knows?
At any rate, she said:
“Why, Miss Philock, Tom Parsons and I have known each other
ever since we were children. He is a sort of distant relation of mine.
Aren’t you, Tom?”
“Ye—yes, Madge,” he almost stammered.
“His mother and my mother are second cousins,” went on the girl,
which was true enough, though Tom had forgotten it. He did not
stop to figure out just what degree of kinship he bore to Madge. He
was satisfied to have it as it was. Miss Philock turned to Tom.
“If I had known this at first,” she said, “I would have allowed you
to send a message to Miss Tyler at once. However strongly young
gentlemen may insist that they are related to my girls, I never
believe them. But if the statement is made by one of my pupils, I
never doubt her. In view of the fact that you have come some
distance, you may step into the parlor, and speak with Miss Tyler for
ten minutes—no longer.”
She opened the door wider. It was quite a different reception from
what Tom had expected, but he was glad enough to see Madge for
even that brief period. He followed her into the parlor, while Miss
Philock passed down the corridor.
“Oh, Tom, I’m so glad to see you!” exclaimed the girl, and she
extended both hands, which Tom held just as long as he decently
could.
“And I’m glad to see you,” he declared. “You’re looking fine!”
“What’s this about Ruth’s brother?” she asked.
“It’s true. He was hurt at football practice this afternoon, and he
was afraid she’d worry. I told him I’d bring a message to her, and
also this letter. It’s from her father, about her mother. Will you give it
to her?”
“Of course. Isn’t it too bad about her poor, dear mother? Ruth is
such a sweet girl. Have you ever met her?”
“I haven’t had the pleasure.”
“I wonder if I’d better introduce you to her,” said Madge musingly.
“She is very fascinating, and—er—well——” She looked at Tom and
laughed.
“Can you doubt me?” asked Tom, also laughing, and he bowed
low, with his hand on his heart.
“Oh, no! Men—especially young men—are never faithless!” she
exclaimed gaily.
“But how can you present me to her, when the ‘ogress,’ as I have
heard her called, bars the way?”
“Hush! She may hear you,” cautioned Madge. “Oh, we have ‘ways
that are dark and tricks that are vain,’ I suppose Miss Philock would
say. I’ll just send a message by wireless, and Ruth will soon be here.
I think it will be safe. Philly, as we call her, will be in her office by
this time.”
Madge stepped to the steam pipes in the room, and with her
pencil tapped several times in a peculiar way.
“That’s a code message to Ruth to come down here,” she
explained.
“It’s a great system,” complimented Tom. “How do you work it?”
“Oh, we have a code. Each girl has a number, and we just tap that
number on the pipes. You know, you can hear a tap all over the
building. Then, after giving the number, we rap out the message,
also by numbers. We just had to invent it. You boys have ever so
many things that we girls can’t, you know. Now tell me all about
football. I suppose you will play?”
“I hope to.”
“And Phil—I mean Mr. Clinton, but I call him Phil, because I hear
Ruth speak of him so often—I think he plays half-back, doesn’t he?”
“No; quarter,” answered Tom.
“I hope to meet him soon,” went on Madge. “Ruth has promised
—— Oh, here she is now,” she interrupted herself to say. “Come in,
Ruth, dear. Here is a sort of forty-second cousin of mine, with a
message about your brother.”
Tom looked up, to see a tall, dark, handsome girl entering the
room. Behind her came a rather stout, light-haired maiden, with
laughing blue eyes.
“A message from my brother!” exclaimed Ruth, and she looked at
Tom in a manner that made his heart beat rather faster than usual.
“Yes, Ruth,” went on Madge; “but nothing serious. I’m glad you
came down, too, Sarah, dear. I want you to meet my cousin.”
“I brought Sarah because I was afraid I didn’t get your pipe
message just right,” explained Ruth. “Did you mean you had
company you wanted to share with me, or that there was a letter for
me? I couldn’t find the code book.”
“It’s both,” declared Madge with a laugh. “But first let’s get the
introductions over with,” and she presented Tom to Ruth, and then
to Miss Sarah Warden, her roommate, as well as Ruth’s.
“Phil has often spoken to me about you, Miss Clinton,” said Tom.
“In fact, he has your picture in our room. It doesn’t look like you—I
mean it doesn’t do you justice—that is—er—I—I mean——”
“Better stop, Tom,” cautioned Madge. “Evidently Ruth has played
havoc with you already. You should study more carefully the art of
making compliments.”
“Miss Clinton needs no compliments other than unspoken ones,”
said Tom, with an elaborate bow.
“Oh, how prettily said!” exclaimed Miss Warden. “Madge, why
didn’t you tell us about your cousin before?”
“It’s time enough now,” was Madge’s rejoinder.
“But what about my brother?” asked Ruth anxiously.
Then Tom told her, and gave her the letter with which Phil had
entrusted him. The young people talked gaily for some minutes
longer, and then Madge, with a look at the clock, said that it was
about time Miss Philock would be back to see that Tom had not
overstayed.
“What a short ten minutes!” he exclaimed, and he looked full in
Ruth Clinton’s eyes.
“Wasn’t it?” she agreed. “However, I hope you will come again—
that is—of course you can’t come here, but perhaps we—I—er—that
is——” She stopped in confusion.
“You’re almost as bad as Tom was!” declared Madge, and there
was just a little change from her former genial tones. She glanced
critically at Tom.
“I expect to come over again,” replied Phil’s chum. “And I hope I
shall see you then, Miss Clinton—see all of you, of course,” he added
quickly.
“It depends on Miss Philock,” said Miss Warden.
“Will you be at the Fairview-Randall football game?” asked Tom.
“Yes,” answered Ruth, for he looked at her.
“I shall see you and Madge, then, I hope, only it’s a long way off,”
and Tom sighed just the least bit.
Madge raised her eyebrows. She might be pardoned for
considering that Tom, in a measure, was her personal property, and
now, the first time he had met Ruth, to hear him talk thus, was
something of a shock.
But she was too proud to show more than a mere hint of her
feelings, and Ruth was, for the time being, entirely unaware that her
friend was a bit jealous.
“Here comes Philly!” exclaimed Sarah Warden, as steps were
heard approaching. “You had better go, Mr. Parsons, if you value
your reputation.”
“Yes,” spoke Madge; “better go, Tom. Sorry you couldn’t stay
longer.”
“So am I,” was his answer, and once more he looked straight at
Ruth. He had thought Madge very pretty, and, while he did not
waver in the least in still thinking her most attractive, he had to
admit to himself that Ruth’s was of a different style of beauty.
“I’m sure I don’t know how to thank you for taking the trouble to
bring me this message and letter,” said Phil’s sister, as she held out
her hand to Tom. He took it in a firm clasp.
“It was only a pleasure,” he said. “Next time I hope to bring better
news.”
“Then there is to be a next time?” she asked archly.
“Of course,” he replied, and laughed.
“Hurry, Tom, or Miss Philock may order you out,” urged Madge.
“You’ve overstayed your leave as it is, and she may punish us for it.
Good-by,” and she held out her hand. Tom clasped it, but a careful
observer, with a split-second watch, might have noted that he did
not hold it quite as long as he had held Ruth’s.
A few minutes later Tom was out on the campus, walking toward
the trolley that would take him to Haddonfield. His brain was in
something of a whirl, and his heart was strangely light.
“My! but she’s pretty!” he exclaimed half aloud. “What fine eyes! I
—I—— Oh, well, what’s the use of talking to yourself?” And with
that sage reflection Tom pursued his silent way.
Back in the parlor the three girls stood for a moment.
“I like your cousin very much, Madge, dear,” said Ruth.
“I shouldn’t wonder!” exclaimed Madge shortly, and she turned
and hurried from the room.
Ruth looked at her in some surprise.
“Whatever has come over Madge?” asked Sarah Warden.
“I can’t imagine,” replied Ruth, and then, with a thoughtful look on
her face, she went to her room.
“Humph! I guess I know,” murmured Miss Warden, as she
followed.
CHAPTER X
A BOTTLE OF LINIMENT
Tom thought of many things as he walked up the silent campus at
Randall, and prepared to go to his room. He went over again every
happening from the time Miss Philock had grudgingly admitted him
at Fairview, until he had bidden Ruth Clinton good-by. Tom had a
very distinct mental picture of two girls’ faces now, whereas, up to
that evening, he had had but one. They were the faces of Ruth and
Madge.
“Hang it all!” he burst out, as he was on the steps of the west
dormitory. “I must be falling in love! This will never do, with the
football season about to open. Better cut it out, Tom Parsons!”
His musing was suddenly interrupted by the appearance of a
figure coming quickly from the teachers’ residence, which was
directly in front of the dormitory building. The figure exclaimed:
“Wait a minute, please.”
“Proctor Zane!” whispered Tom to himself. “He thinks he’s caught
me. Probably he doesn’t know I’ve got a permit. I’ll have some fun
with him.”
A moment later the proctor stood beside Tom.
“Are you aware of the hour?” asked Mr. Zane, in what he meant to
be a sarcastic tone.
“I—I believe it’s nearly two o’clock,” replied Tom. “I will tell you
exactly in a moment, as soon as I look at my watch,” and with a
flourish he drew his timepiece from his pocket. “It lacks just eight
minutes of two,” he added.
“I didn’t ask you the time!” exclaimed the proctor.
“I beg your pardon, sir; I thought you did,” spoke Tom.
“Aren’t you getting in rather late?” asked the official, as he drew
out his book and prepared to enter Tom’s name.
“Well, it might be called late,” admitted Tom, as if there was some
doubt about it. “That is, unless you choose to look at it from another
standpoint, and call it early morning. On the whole, I think I prefer
the latter method. It is more comforting, Mr. Zane.”
“None of your impertinence, Parsons!” exclaimed the proctor. “You
are out after hours, and you will report to my office directly after
chapel. This matter of students staying out must be broken up.”
“I agree with you,” went on Tom easily, “but I’m afraid I can’t
report to you after chapel to-morrow, or, rather, to-day, Mr. Zane.”
“You can’t? What do you mean, Parsons?”
“Why, you see, I have to attend a lecture by Moses—I beg your
pardon—Dr. Churchill—at that hour.”
The proctor, as Tom could see in the light of the hall lamp, as the
rays streamed from the glass door of the dormitory, looked pained at
the appellation of “Moses” to the venerable head of the college. The
boys all called Dr. Churchill that among themselves, though they
meant no disrespect. They had evolved the title from his name; from
the fact that, as one of the first students put it, the original Moses
went up on a hill to establish the first church—hence Church—Hill;
and thus “Moses.”
“I am sure Dr. Churchill will excuse you when he knows the
circumstances, Parsons,” went on the proctor with a malicious smile.
“You will report to me for being out after hours without permission.”
“Oh, but I have permission,” spoke Tom, as he drew out a note
which the president had given him. “I beg your pardon for not
mentioning it before. Very stupid of me, I’m sure,” and this time it
was Tom’s turn to grin.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like