Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Engineering LibreTexts

3.8: Generalization

( \newcommand{\kernel}{\mathrm{null}\,}\)

As written, the previous example always adds up the first 10 elements of the sequence, but we might be curious to know what happens to total as we increase the number of terms in the series. If you’ve studied geometric series, you might know that this series converges on 2; that is, as the number of terms goes to infinity, the sum approaches 2 asymptotically.

To see if that’s true for our program, we can replace the constant 10 in Listing 3.1 with a variable named n:

Listing 3.2: Updating our code from Listing 3.1 to have a variable number of terms

A1 = 1;
total = 0;
for i=1:n
    a = A1 * (1/2)^(i-1);
    total = total + a;
end
ans = total

The code in Listing 3.2 can now compute any number of terms, with the precondition that you have to set n before you execute the code. I put this code in a file named series.m, then ran it with different values of n:

>> n=10; series
total = 1.99804687500000

>> n=20; series
total = 1.99999809265137

>> n=30; series
total = 1.99999999813735

>> n=40; series
total = 1.99999999999818

It sure looks like it’s converging on 2.

Replacing a constant with a variable is called generalization. Instead of computing a fixed, specific number of terms, the new script is more general; it can compute any number of terms. This is an important idea we’ll come back to when we talk about functions.


This page titled 3.8: Generalization is shared under a CC BY-NC 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.

Support Center

How can we help?