Scroll to Top

Virtual Math Learning Center

Virtual Math Learning Center Texas A&M University Virtual Math Learning Center

Generating and Plotting Partials Sums of a Series in Python

Author: David Manuel

In this video, we use Python to compute and plot the partial sums of a series in order to estimate the sum of the corresponding infinite series. Then we use Python to calculate the exact value of the series.

Transcript 26

Problem: Given the series 
\[\sum_{n=1}^\infty \frac{(-1)^{n+1}}{n^2}\]

  1. Find and plot the first 20 partial sums.
  2. Find the exact sum of the series.

Python Code: 
Given the series sum from 1 to infinity of (-1)^(n+1)/n^2
a) Find and plot the first 20 partial sums
b) Find the exact sum of the series

from sympy import *
import numpy as np

n=symbols('n',positive=True,integer=True)
a=(-1)**(n+1)/n**2
n1to20=range(1,21)
a1to20=[a.subs(n,i).evalf() for i in n1to20]
print(a1to20)
s1to20=np.cumsum(a1to20)
print(s1to20)

matplotlib notebook

import matplotlib.pyplot as plt
plt.plot(n1to20,s1to20,'o')

from mpmath import nsum,inf
S=nsum(lambda n:(-1)**(n+1)/n**2,[1,inf])
print('The sum of the series is',S)

Open Python Notebook File

See more videos from this section