Ask Your Question
1

Defined variable in recursive function

asked 2018-12-23 00:39:07 +0100

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.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2018-12-23 02:14:31 +0100

tmonteil gravatar image

updated 2018-12-23 02:14:58 +0100

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
edit flag offensive delete link more

Comments

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

Quotenbanane gravatar imageQuotenbanane ( 2018-12-23 02:19:35 +0100 )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-23 02:57:07 +0100 )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

Stats

Asked: 2018-12-23 00:39:07 +0100

Seen: 811 times

Last updated: Dec 23 '18