3.7: Series
( \newcommand{\kernel}{\mathrm{null}\,}\)
In mathematics, a series is the sum of the elements of a sequence. It’s a terrible name, because in common English, “sequence” and “series” mean pretty much the same thing, but in math, a sequence is a set of numbers, and a series is an expression (a sum) that has a single value. In math notation, a series is often written using the summation symbol ∑.
For example, the sum of the first 10 elements of A is 10∑i=1Ai
A for
loop is a natural way to compute the value of this series:
Listing 3.1: A program that calculates a simple series
A1 = 1;
total = 0;
for i=1:10
a = A1 * (1/2)^(i-1);
total = total + a;
end
ans = total
Let’s walk through what’s happening here. A1
is the first element of the sequence, so we assign it to be 1
; we also create total
, which will store the cumulative sum. Each time through the loop, we set a
to the ith element and add a
to the total
. At the end, outside the loop, we store total
as ans
The way we’re using total
is called an accumulator, that is, a variable that accumulates the result a little bit at a time.
This example computes the terms of the series directly. As an exercise, write a script named series.m that computes the same sum by computing the elements recurrently. You will have to be careful about where you start and stop the loop.