Generating and Plotting Sequences
In this example, we use Python to numerically, graphically, and analytically find the limit of a sequence. Suppose we have the sequence defined by a(n) = n*sin(pi/n). We will list the first 20 terms of the sequence, then plot the first 50 terms, and finally use Python’s built-in limit command. Notice that this sequence is just a function whose domain is all positive integers, so we can create the sequence by using the subs command, and we can use list comprehension to generate all the terms in one command. So after importing our sympy package, we define n as a symbolic variable, but we can specify the restrictions that n must be positive and an integer using the options positive=True and integer=True. Next we define our function a. Now we use list comprehension by defining a variable a1to20 as a list found by substituting i in place of n for any i from 1 to 20. Checking online documentation or a previous video will show you that the range(1,21) option creates the integers from 1 INCLUSIVE to 21 EXCLUSIVE (so 1 to 20). When we print the values, we see that Python gives exact answers. We can force them to be decimal approximations by adding the .evalf() command after our subs command. Numerically, we see the values are approaching a little more than 3.12. To plot the terms, we need a numerical plot command, which is located in the package matplotlib.pyplot. So after our matplotlib notebook command to print the graph in Jupyter, we import this package and create a shortcut plt. We create the variable n1to50 using the range command, then use list comprehension to create the sequence a1to50 as before. Now we run the numeric plot command using plt.plot, and since we just want the points, we indicate this using the ‘o’ option. The values appear to be approaching something between 3 and 3.5. Finally, we use the limit command on a, using oo for infinity, to see that our sequence approaches pi, as estimated.