Link Search Menu Expand Document (external link)

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

See all solutions.

Task

In mathematics, a sequence is an infinite list of values, typically real numbers, often written a0,a1,a2,, or collectively as an.

(Let’s assume that sequences are indexed starting with index 0, at a0, even though some definitions start with index 1, at a1, instead.)

How can we express sequences 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

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 an=1n+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 ).

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

[1,12,13,14,]

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

1
seq[20]

121

1
seq[:10]

[1, 12, 13, 14, 15, 16, 17, 18, 19, 110]

You can compute the limit of a sequence,

limnan.
1
limit( a_n, n, oo )

0

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)