Generating and Plotting Partial Sums of a Series
In this example, we use Python to compute and plot the partial sums of a series in order to estimate the sum of the corresponding infinite series. We wish to estimate the sum from n=1 to infinity of (-1)n+1/n2 using the first 20 partial sums. We begin by importing our sympy package, defining n as a symbolic variable (forcing it to be positive and an integer), and define a to be the terms of the series, (-1)^n/n^2. Our process for computing the first 20 partial sums by hand is as follows:
1) Substitute n=1 to 20 into the expression a (subs)
2) Use the command cumsum (short for “cumulative sum” so watch that pronunciation!) to generate the list of partial sums.
3) Print and/or plot the list of partial sums against n
To simplify step 1, we can use list comprehension to substitute everything in one command line. So we will define n as the list of numbers from 1 to 20. This is easily done using the range command. NOTE that the command range(a,b) creates a list of integers from a INCLUSIVE to b EXCLUSIVE much like the arange command you may have seen in a previous video. So we define n1to20=range(1,21). Now use list comprehension and define a1to20 as the list of a substituting n=i for i in the list n1to20. Since there are only 20 terms, we can print them to check our intermediate steps. We notice Python gives us exact fractions, so we can put the .evalf() command at the end to convert them to floating point. For step 2, we define s1to20=cumsum(a1to20). For step 3, we print the list to see that indeed, the terms are being added as we go. To plot this list of values, we use the numerical plot command found in the package matplotlib.pyplot, so we first import this package using a shorthand notation plt, then plt.plot n1to20 vs s1to20, indicating with the ‘o’ option we want points rather than a connected graph. Both the list of numerical values and the graph give us an idea of what value, if any, the series is converging to. In many cases, we can find this exact sum using the nsum command, which is located in the package mpmath. So we import this command (since there is no equivalent command in sympy) and the command inf, which is how nsum recognizes infinity. Finally, nsum does not recognize symbolic expressions, so we create a function using the lambda command. Putting all this together, we have S=nsum(lambda n:(-1)**n/n**2,[1,inf]) and discover that the series converges to pi^2/12.