Plotting a Function and Partial Sums of its Power Series
In this example, we visualize the partial sums of a Power Series along with the function represented by the series. For example, we know that the power series for f(x)=arctan(x) is the sum from 0 to infinity of (-1)n x2n+1/(2n+1). We will graph the 3rd,5th, and 10th partial sum of the series along with the function. The steps for finding the Nth partial sums by hand are:
1) Substitute 0 to N into an. (Python command: subs)
2) Add these terms together (Python command: sum)
So as always, we load our sympy package into Python, define n as a symbolic positive integer and x as a symbolic variable, then define our expression a which represents the nth term of the series, and f which represents the function arctan(x). With list comprehension, Step 1 can be done on one line. So we will define the variable a1to3 as the list formed by substituting into a n=i, for i from 0 to 3. Remember the range(a,b) command creates a list of integers from a INCLUSIVE to b EXCLUSIVE. If we only put one number in our range command, the list starts by default at 0, which is what we want. For step 2, we define an expression s3 as just the sum of the list a1to3 Notice if I print s3, we end up with a polynomial, called a Taylor Polynomial. We now repeat these two commands for i from 0 to 5 (range(6) ) and for i from 0 to 10 (range(11) ). Finally, we wish to plot these 4 functions. We can plot them all in the same command using tuples, and we will use a domain of [-1.5,1.5] with a y-range (using the ylim option) of [-1,1]. If we wanted to distinguish them by color, we can assign a name to our plot, like plotf, then change the color of one graph by using indices. A reminder that when Python counts elements of a list, matrix, or tuple that it starts counting at zero, so if we want to change the second graph to red, for example, we refer to it using plotf[1], then use our dot notation and the line_color option. We will also change the third graph to yellow, and the fourth graph to black (âkâ). We can then redisplay our new graph using the .show() option. We can see from the graph that 1) the polynomials diverge from the graph of f outside the radius of convergence, and 2) the more terms we add, the more accurate the partial sum is compared to the function within the interval of convergence.