Sympy - define function implicitly and evaluate with specified initial conditions

Viewed 110

Let's consider the following simple recurrence relation

Can I use sympy to symbolically compute the resulting expression at index n recursively? I'm looking for a generic way to do this, i.e. I do not want to have an explicit solution to the above equation (as it may in general be to difficult for sympy to solve).

2 Answers

Based on http://gerin.perso.math.cnrs.fr/Enseignements/Symbolic3_Solutions.pdf I was able to write a solution

from sympy import *
from IPython.display import display
init_printing()

a, b = symbols('a b')
y = [1,1] # store sequence in list, start with initial conditions
N = 5

for n in range(2, N+1):
    y += [simplify(a*y[-1]+b*y[-2])]
    display(y[-1])

This gives the output

+
(+)+
((+)+)+(+)
(((+)+)+(+))+((+)+)

You can use rsolve:

In [10]: from sympy import *

In [11]: y = Function('y')

In [12]: a, b, n = symbols('a, b, n')

In [13]: eq = Eq(y(n), a*y(n-1) + b*y(n-2))

In [14]: eq
Out[14]: y(n) = a⋅y(n - 1) + b⋅y(n - 2)

In [15]: rsolve(eq, y(n))
Out[15]: 
                      n                         n
   ⎛       __________⎞       ⎛       __________⎞ 
   ⎜      ╱  2       ⎟       ⎜      ╱  2       ⎟ 
   ⎜a   ╲╱  a  + 4⋅b ⎟       ⎜a   ╲╱  a  + 4⋅b ⎟ 
C₀⋅⎜─ - ─────────────⎟  + C₁⋅⎜─ + ─────────────⎟ 
   ⎝2         2      ⎠       ⎝2         2      ⎠ 

https://docs.sympy.org/latest/modules/solvers/solvers.html#sympy.solvers.recurr.rsolve

Related