Ask Your Question
1

Defined variable in recursive function

asked 6 years ago

Quotenbanane gravatar image
@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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
0

answered 6 years ago

tmonteil gravatar image

updated 6 years ago

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
Preview: (hide)
link

Comments

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

Quotenbanane gravatar imageQuotenbanane ( 6 years ago )

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 ( 6 years ago )

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

Stats

Asked: 6 years ago

Seen: 933 times

Last updated: Dec 23 '18