In this chapter, we extend the idea of looping to develop an important technique: the accumulator pattern, using a variable to build up gradually to a desired value. The examples in the chapter are mathematically interesting—specifically, most concern approximating the value of Π, the ratio of a circle's circumference to its diameter.
Unfortunately, what is mathematically interesting is not interesting to everybody. However, the accumulator pattern is much more generally useful than this, and I will add other kinds of examples. In general, the accumulator pattern is useful for computing sums and products, and things that depend on them, such as averages. For example, given the rainfall on each day of the month, what is the total rainfall, and what is the average rainfall per day?
The math module provides a number of useful functions and the constants
e. Internally, it probably uses the accumulator technique for many of its functions, although this is hidden from us.
We also learn another important technique for controlling a computation: the use of boolean values (true and false) to make decisions, using the
if statement. For example, if your purchase is for $100 or more, you are entitled to a 10% discount, or for free shipping.
The chapter concludes with the Monte Carlo simulation technique, which uses randomness to compute approximate values (again, in the textboook, it's an approximate value for π). This technique combines the accumulator pattern, decision making, and randomness, using the
random module to generate (pseudo-)random numbers. It is frequently useful to get an approximate answer, where getting an exact answer would be too difficult or impossible.