# function parameters as sum limits

I am completely new to sage, so I am afraid that this should be a very standard well known issue. Sorry for that.

I need to define a function one of whose parameters is a limit of a sum. I tried:

d,n,i = var('d,n,i')
def N(d,n):
if n==1:
return 1
else:
return sum(N(d,i),i,1,n-1)


But sage complains with a RuntimeError. Why is that? I suppose that for some reason the parameter n from the function is not assigned to the variable limit n-1 in the sum. I this correct? How can I fix that?

edit retag close merge delete

Sort by » oldest newest most voted

I will elaborate on the other answer, which is correct; you could use

sage: def N(d,n):
....:  if n==1:
....:         return 1
....:  else:
....:         return sum(N(d,i) for i in range(1,n))


Ordinarily, this should have just returned some sort of evident error that you couldn't do it (such as below). But because of a subtlety in how you defined your function, instead you never actually discovered this in your sum. Your sum instead kept returning itself when n=2, so you got a RuntimeError about infinite recursion.

If you do sum? in the terminal or notebook, you should get documentation that includes this:

   Warning: This function only works with symbolic expressions. To
sum any other objects like list elements or function return
values, please use python summation, see
http://docs.python.org/library/functions.html#sumIn particular,
this does not work:

sage: n = var('n')
sage: mylist = [1,2,3,4,5]
sage: sum(mylist[n], n, 0, 3)
Traceback (most recent call last):
...
TypeError: unable to convert n to an integer

sage: sum(mylist[n] for n in range(4))
10


Also, where does d occur in your function? It seems to be a dummy variable in the truest sense of the word - completely silent, that is.

more

1

Thank you for the clarification; and yes d is just a remainder from the original (more complicated) function I needed to compute. Should I remove it from the question?

( 2019-04-11 15:24:25 +0200 )edit

Probably not at this point, since then we would have to update all the answers.

( 2019-04-12 04:12:49 +0200 )edit

Use this:

return sum(N(d,i) for i in range(1,n))


Your syntax is for symbolic sums only. And remove your first line.

more