Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/notebooks/chap06.ipynb
Views: 531
Modeling and Simulation in Python
Chapter 6
Copyright 2017 Allen Downey
Code from the previous chapter
System objects
We can rewrite the code from the previous chapter using system objects.
And we can encapsulate the code that runs the model in a function.
We can also encapsulate the code that plots the results.
Here's how we run it.
Proportional growth
Here's a more realistic model where the number of births and deaths is proportional to the current population.
I picked a death rate that seemed reasonable and then adjusted the birth rate to fit the data.
Here's what it looks like.
The model fits the data pretty well for the first 20 years, but not so well after that.
Factoring out the update function
run_simulation1
and run_simulation2
are nearly identical except the body of the loop. So we can factor that part out into a function.
The name update_func
refers to a function object.
Which we can confirm by checking its type.
run_simulation
takes the update function as a parameter and calls it just like any other function.
Here's how we use it.
Remember not to put parentheses after update_func1
. What happens if you try?
Exercise: When you run run_simulation
, it runs update_func1
once for each year between t_0
and t_end
. To see that for yourself, add a print statement at the beginning of update_func1
that prints the values of t
and pop
, then run run_simulation
again.
Combining birth and death
Since births and deaths get added up, we don't have to compute them separately. We can combine the birth and death rates into a single net growth rate.
Here's how it works:
Exercises
Exercise: Maybe the reason the proportional model doesn't work very well is that the growth rate, alpha
, is changing over time. So let's try a model with different growth rates before and after 1980 (as an arbitrary choice).
Write an update function that takes pop
, t
, and system
as parameters. The system object, system
, should contain two parameters: the growth rate before 1980, alpha1
, and the growth rate after 1980, alpha2
. It should use t
to determine which growth rate to use. Note: Don't forget the return
statement.
Test your function by calling it directly, then pass it to run_simulation
. Plot the results. Adjust the parameters alpha1
and alpha2
to fit the data as well as you can.