# Defined variable in recursive function

@cached_function
def Folge2(n):
k = var('k')
if n < 1:
return 1
else:
return (-1/(n+1)*sum((binomial(n+1,k)*Folge2(k)),k,0,n-1))

print Folge2(1)


Hello. I've got a problem with this program right here.

Sage is giving back a "RuntimeError: maximum recursion depth exceeded while calling a Python object". It is likely because i'm calling Folge2(k) again with k as defined variable.

How can i avoid this?

Best regards.

edit retag close merge delete

Sort by » oldest newest most voted

You do not need to make symbolic computation to get a rational number at the end, you can just do:

sage: @cached_function
....: def Folge2(n):
....:     if n < 1:
....:         return 1
....:     else:
....:         return -1/(n+1)*sum(binomial(n+1,k)*Folge2(k) for k in range(n))


Then:

sage: Folge2(1)
-1/2
sage: Folge2(2)
1/6
sage: Folge2(3)
0
sage: Folge2(4)
-1/30
sage: Folge2(5)
0
sage: Folge2(6)
1/42

more

Thanks a lot sir :) And say hello to the recursive function of the Bernoulli-numbers.

You'll get a much more efficient routine (and one that can extend beyond n=1000, which is Python's default maximum recursion level) if you iteratively compute and store Folge2(0),Folge2(1),Folge2(2),... and use the stored numbers to compute the next one. You could do something similar for the binomials if you really want fast computation.