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 :
JavaScript
x
6
1
from sympy import *
2
n = symbols('n', integer=True)
3
u0 = 2
4
r = 5
5
ari_seq = sequence(u0 + n * r, (n, 0, 5))
6
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:
JavaScript
1
18
18
1
from sympy import *
2
from sympy.series.sequences import RecursiveSeq
3
4
n = symbols("n", integer=True)
5
y = Function("y")
6
r, q = symbols("r, q")
7
8
# note the initial term '2' could also be symbolic
9
arith = RecursiveSeq(y(n-1) + r, y(n), n, [2])
10
geo = RecursiveSeq(y(n-1)*q, y(n), n, [2])
11
12
# calculate a few terms
13
arith[:5] # [2, r + 2, 2*r + 2, 3*r + 2, 4*r + 2]
14
geo[3:5] # [2*q**3, 2*q**4]
15
16
# to use with rsolve you'll need to unpack the RecursiveSeq into ordinary sympy expressions:
17
rsolve(geo.recurrence.rhs - geo.recurrence.lhs, geo.recurrence.lhs, [geo[0]]) # 2*q**n
18