Ask Your Question

Defined variable in recursive function

asked 2018-12-22 17:39:07 -0500

Quotenbanane gravatar image
def Folge2(n):
    k = var('k')
    if n < 1:
        return 1
        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 flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2018-12-22 19:14:31 -0500

tmonteil gravatar image

updated 2018-12-22 19:14:58 -0500

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))


sage: Folge2(1)
sage: Folge2(2)
sage: Folge2(3)
sage: Folge2(4)
sage: Folge2(5)
sage: Folge2(6)
edit flag offensive delete link more


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

Quotenbanane gravatar imageQuotenbanane ( 2018-12-22 19:19:35 -0500 )edit

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.

nbruin gravatar imagenbruin ( 2018-12-22 19:57:07 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2018-12-22 17:39:07 -0500

Seen: 36 times

Last updated: Dec 22 '18