# How to define a mathematical series (in Python, using SymPy)

## Task

In mathematics, a series is a sum of values from a sequence, typically real numbers. Finite series are written as $a_0+a_1+\cdots+a_n$, or

\[\sum_{i=0}^n a_i.\]Infinite series are written as $a_0+a_1+a_2+\cdots$, or

\[\sum_{n=0}^\infty a_n.\]How can we express series in mathematical software?

Related tasks:

## Solution

This answer assumes you have imported SymPy as follows.

1
2

from sympy import * # load all math functions
init_printing( use_latex='mathjax' ) # use pretty math output

We define here the same sequence we defined in the task entitled how to define a mathematical sequence.

1
2
3
4

var( 'n' ) # use n as a symbol
a_n = 1 / ( n + 1 ) # formula for a term
seq = sequence( a_n, (n,0,oo) ) # build the sequence
seq

$\displaystyle \left[1, \frac{1}{2}, \frac{1}{3}, \frac{1}{4}, \ldots\right]$

We can turn it into a mathematical series by simply replacing the word
`sequence`

with the word `Sum`

. This does not compute the answer, but
just writes the series for us to view. In this case, it is an infinite
series.

1

Sum( a_n, (n,0,oo) )

$\displaystyle \sum_{n=0}^{\infty} \frac{1}{n + 1}$

You can compute the answer by appending the code `.doit()`

to the above code,
which asks SymPy to “do” (or evaluate) the sum.

1

Sum( a_n, (n,0,oo) ).doit()

$\displaystyle \infty$

In this case, the series diverges.

We can also create and evaluate finite series by replacing the `oo`

with a number.

1

Sum( a_n, (n,0,10) ).doit()

$\displaystyle \frac{83711}{27720}$

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)