Skip to content
Advertisement

Sympy – Arithmetic and geometric sequence in recursive form

I would like to define arithmetic and geometric sequences in recursive form like

  • Un+1 = Un + r (u0 n>0)
  • Un+1 = qUn (u0 n>0)

In Sympy, one can define in closed form an arithmetic sequence like this :

from sympy import *
n = symbols('n', integer=True)
u0 = 2
r = 5
ari_seq = sequence(u0 + n * r, (n, 0, 5))

How can I define (not solve) this sequence in recursive form (Un+1 = Un + r) ?

Advertisement

Answer

You’ll need to define the recurrence relation using Function.

There is also a RecursiveSeq that may help

Example:

from sympy import *
from sympy.series.sequences import RecursiveSeq

n = symbols("n", integer=True)
y = Function("y")
r, q = symbols("r, q")

# note the initial term '2' could also be symbolic
arith = RecursiveSeq(y(n-1) + r, y(n), n, [2])
geo = RecursiveSeq(y(n-1)*q, y(n), n, [2])

# calculate a few terms
arith[:5] # [2, r + 2, 2*r + 2, 3*r + 2, 4*r + 2]
geo[3:5] # [2*q**3, 2*q**4]

# to use with rsolve you'll need to unpack the RecursiveSeq into ordinary sympy expressions:
rsolve(geo.recurrence.rhs - geo.recurrence.lhs, geo.recurrence.lhs, [geo[0]])  # 2*q**n
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement