# Defining a function of the form $f(x_1,x_2,...,x_n)=\sum_{i=0}^n x_i$

How can I define a function of the form $$f(x_1,x_2,...,x_n)=\sum_{i=0}^n x_i$$ I tried the following
sage: n = 2
sage: x = [ var('x_%d' % i) for i in range(n) ]
sage: f(x)=sum(x[i],i,0,n)
The last line gives me the error
"TypeError: 'sage.symbolic.expression.Expression' object does not support indexing".

edit retag close merge delete

Sort by ยป oldest newest most voted

You're getting the TypeError because you're double-assigning x: in your second line, you make it a list of variables, but in the third you redefine it as a symbolic variable. The f(x)=sum(x[i],i,0,n) line is translated as

sage: preparse("f(x) = sum(x[i], i, 0, n")
'__tmp__=var("x"); f = symbolic_expression(sum(x[i], i, Integer(0), n).function(x)'


Unfortunately we can't simply rename x to xx: the "f(x,y) = x+y" syntax requires explicit specification of the variables, and you can't pass it a list. So for a fixed n (which is the only case I really know how to handle offhand) I would probably do this instead:

sage: n = 2
sage: xx = [var('x_%d' % i) for i in range(n)]
sage:
sage: f = sum(xx).function(*xx)
sage: f
(x_0, x_1) |--> x_0 + x_1


[Here I took advantage of the * operator in *xx, which turns f(*[a,b,c]) into f(a,b,c).]

Oh, I've just noticed that I used [0..n-1] as the indices and I think you're using [0..n], but that's easy to change.

more

@DSM Thanks DSM, your answer is enlightening

( 2011-12-20 03:37:42 -0600 )edit

What about this? Assume $x$ is a list. Then:

def f(x):
return sum(x)


(I just think it's easier to remember than the answer by DSM.)

more

Python functions and Sage functions are slightly different -- there are cases where you need to use the latter, and the calling syntax differs -- but I agree there are many times when this would work okay.

( 2011-12-21 02:13:38 -0600 )edit