Skip to Content
Think Complexity, 2nd Edition
book

Think Complexity, 2nd Edition

by Allen B. Downey
July 2018
Beginner
198 pages
4h 33m
English
O'Reilly Media, Inc.
Content preview from Think Complexity, 2nd Edition

Chapter 10. Herds, Flocks, and Traffic Jams

The agent-based models in the previous chapter are based on grids: the agents occupy discrete locations in two-dimensional space. In this chapter we consider agents that move in continuous space, including simulated cars on a one-dimensional highway and simulated birds in three-dimensional space.

Traffic Jams

What causes traffic jams? Sometimes there is an obvious cause, like an accident, a speed trap, or something else that disturbs the flow of traffic. But other times traffic jams appear for no apparent reason.

Agent-based models can help explain spontaneous traffic jams. As an example, I implement a highway simulation based on a model in Mitchell Resnick’s book, Turtles, Termites and Traffic Jams.

Here’s the class that represents the “highway”:

class Highway:

    def __init__(self, n=10, length=1000, eps=0):
        self.length = length
        self.eps = eps

        # create the drivers
        locs = np.linspace(0, length, n, endpoint=False)
        self.drivers = [Driver(loc) for loc in locs]

        # and link them up
        for i in range(n):
            j = (i+1) % n
            self.drivers[i].next = self.drivers[j]

n is the number of cars, length is the length of the highway, and eps is the amount of random noise we’ll add to the system.

locs contains the locations of the drivers; the NumPy function linspace creates an array of n locations equally spaced between 0 and length.

The drivers attribute is a list of Driver objects. The for loop links them so each Driver contains a reference to the next. The highway ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Essential Algorithms, 2nd Edition

Essential Algorithms, 2nd Edition

Rod Stephens
Think Data Structures

Think Data Structures

Allen B. Downey
Just Enough Math

Just Enough Math

Paco Nathan

Publisher Resources

ISBN: 9781492040194Errata Page