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

See all solutions.

In mathematics, a sequence is an infinite list of values, typically real numbers, often written $a_0,a_1,a_2,\ldots$, or collectively as $a_n$.

(Letâ€™s assume that sequences are indexed starting with index 0, at $a_0$, even though some definitions start with index 1, at $a_1$, instead.)

How can we express sequences in mathematical software?

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


Sequences are typically written in terms of an independent variable $n$, so we will tell SymPy to use $n$ as a symbol, then define our sequence in terms of $n$.

We define a term of an example sequence as $a_n=\frac{1}{n+1}$, then build a sequence from that term. The code (n,0,oo) means that $n$ starts counting at $n=0$ and goes on forever (with oo being the SymPy notation for $\infty$).

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]$

You can ask for specific terms in the sequence, or many terms in a row, as follows.

1
seq[20]


$\displaystyle \frac{1}{21}$

1
seq[:10]


$\displaystyle \left[ 1, \ \frac{1}{2}, \ \frac{1}{3}, \ \frac{1}{4}, \ \frac{1}{5}, \ \frac{1}{6}, \ \frac{1}{7}, \ \frac{1}{8}, \ \frac{1}{9}, \ \frac{1}{10}\right]$

You can compute the limit of a sequence,

$\lim_{n\to\infty} a_n.$
1
limit( a_n, n, oo )


$\displaystyle 0$