“91974˙CH02˙ﬁnal” — 2012/12/14 — 13:58 — page 54 — #10
54 CHAPTER 2
You will also notice another new Python function, print. The print function shows both the
number of sides used and the result returned from the function. In a sense, this is nothing
more than explicitly calling the print action as was described as part of the read–eval–print
loop. It is possible to print more than one value by including multiple parameters.
2.6 Repeat the loop in Session 2.4. In addition to the value of pi, print out the diﬀerence
between the value calculated by the archimedes function and math.pi. How many
sides does it take to make the two close?
2.7 Modify the archimedes function to take the radius as a parameter. Can you get a
better answer more quickly using a larger circle?
2.5 Accumulator Approximations
The pi approximation techniques that follow will use mathematics based on what are called
inﬁnite series and inﬁnite product expansions. The basic idea is that by adding or multi-
plying an inﬁnite number of arithmetic terms, we can get closer and closer to the actual
value we are trying to compute. Although the mathematics of these approaches is beyond
the scope of this book, the patterns provide excellent examples of arithmetic processing.
2.5.1 The Accumulator Pattern
In order to use these techniques, we will need to introduce another important problem-
solving pattern known as the accumulator pattern. This common pattern comes up
very often. Your ability to recognize the pattern and then implement it will be especially
useful as you encounter new problems that need to be solved.
As an example, consider the simple problem of computing the sum of the ﬁrst ﬁve integer
numbers. Of course, this is really quite easy since we can just evaluate the expression
1 + 2 + 3 + 4 + 5. But what if we wanted to sum the ﬁrst ten integers? Or perhaps the ﬁrst
hundred? In this case we would ﬁnd that the size of the expression would become quite
long. To remedy this, we can develop a more general solution that uses iteration.
Examine the Python code shown in Session 2.5. As you can see, the variable acc starts oﬀ
with a value of 0, sometimes called the initialization. Recall that the statement for x in
range(1,6): will cause the loop variable x to iterate over the values from 1 to 5. Figure 2.5
shows how this can then be used to create the running sum. Every time we pass through