Solving recurrence using sympy
Asked Answered
R

1

7

I was trying to solve recurrence relation of fibonacci series using sympy. I got an answer which is different from that of the text book. Dont know where I got it wrong.

My sympy code

from sympy import *
f=Function('f')
var('y')
var('n',integer=True)
f=y(n)-y(n-1)+(n-2)
rsolve(f,y(n))

And output is

C0 + (-n + 1)*(n/2 - 1)

Radar answered 2/9, 2016 at 17:12 Comment(5)
The output is correct for the recurrence equation f (=0) you provide. Are you sure this is the correct form of f? I believe the recurrence relation of fibonacci series is f = y(n) - y(n-1) - y(n-2) (=0)Papaverine
In addition to what @Papaverine mentioned, rsolve allows for initial conditions. Two are typically given for the fibonacci.Willman
@Papaverine How to give initial conditions?Radar
@Radar You provide a dictionary as initial conditions. See the rsolve documentationPapaverine
@Papaverine Gave as print rsolve(f,y(n),{y(0):1,y(1):1}) and getting None are result.Radar
P
11

Here's a complete code for solving the Fibonacci recursion. Please note carefully the correct use of Function and symbols.

from sympy import *
y = Function('y')
n = symbols('n',integer=True)
f = y(n)-y(n-1)-y(n-2)
rsolve(f,y(n),{y(0):0, y(1):1})

sqrt(5)*(1/2 + sqrt(5)/2)**n/5 - sqrt(5)*(-sqrt(5)/2 + 1/2)**n/5

Papaverine answered 3/9, 2016 at 7:39 Comment(1)
Text gave the answer as imgur.com/a/YUi1t Also y(0) is 1 for fabanocci (I gave like that).Radar

© 2022 - 2024 — McMap. All rights reserved.