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)
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) .
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 .
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With