Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving recurrence using sympy

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)

like image 477
user567879 Avatar asked Sep 02 '16 17:09

user567879


People also ask

How do you solve a linear equation SymPy?

After the symbols and equations are defined, we can use SymPy's solve() function to compute the value of x and y. The first argument passed to the solve() function is a tuple of the two equations (eq1, eq2) . The second argument passed to the solve() function is a tuple of the variables we want to solve for (x, y) .

How do you evaluate a SymPy expression?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .

Is there a solve function in Python?

The solve() function takes two arguments, a tuple of the equations (eq1, eq2) and a tuple of the variables to solve for (x, y) . The SymPy solution object is a Python dictionary. The keys are the SymPy variable objects and the values are the numerical values these variables correspond to.

How define SymPy function?

sympy. Function is for undefined functions. Like if f = Function('f') then f(x) remains unevaluated in expressions. Then f(Symbol('x')) will give a symbolic x**2 + 1 and f(1) will give 2 .


1 Answers

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

like image 195
Stelios Avatar answered Sep 25 '22 08:09

Stelios