Session 13

Using a Loop to Find a Tolerance

CS 1510
Introduction to Computing

Approximating Infinite Series with Arbitrary Precision

Our solutions to approximate this infinite series:

    1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - ...

... and this infinite series:

    1/0! + 1/1! + 1/2! + 1/3! + 1/4! + ...

... asked the user to tell us how many terms to compute. We then used that value as the range of a counted loop, such as:

    for i in range(terms):
        term_value = 1.0 / divisor
        if i % 2 == 0:
            accum += term_value
            accum -= term_value
        divisor += 2

Then we checked to see how close we were to the expected value, π/4 or e. For example,

    guess = 4 * accum

    print('Python say : ', math.pi)
    print('Program say: ', guess)
    print('Difference : ', guess - math.pi)

Sometimes the number was close to the the expected value, and other times, it wasn't, depending on how many terms we computed and how quickly the series converged. The first series above converges slowly, while the second converges very quickly.

We can turn this process inside out. We ask the user how close an approximation she wants, and then we compute however many terms we need to reach an acceptable value:

  1. make an initial guess
  2. while guess is outside desired range

Because the series converge, we know that we can get as close as we want -- eventually. We just need to compute enough terms! ... with one caveat: we can only get as close as the number of digits can Python represent.

Such a program might look something like or Notice the construction of the

The key ideas in these examples:

Now, we are equipped to answer an interesting question: How quickly does a series converge?

Exam 1

The rest of the period is devoted to Exam 1

Wrap Up

Eugene Wallingford ..... ..... October 7, 2014