Ask Your Question

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

asked 2011-12-20 09:52:14 +0200

Nicolas Essis-Breton gravatar image

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 flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2011-12-20 10:12:40 +0200

DSM gravatar image

updated 2011-12-20 10:14:54 +0200

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: 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.

edit flag offensive delete link more


@DSM Thanks DSM, your answer is enlightening

Nicolas Essis-Breton gravatar imageNicolas Essis-Breton ( 2011-12-20 10:37:42 +0200 )edit

answered 2011-12-20 12:41:12 +0200

Zatrapadoo gravatar image

updated 2011-12-20 12:43:07 +0200

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

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

DSM gravatar imageDSM ( 2011-12-21 09:13:38 +0200 )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: 2011-12-20 09:52:14 +0200

Seen: 1,292 times

Last updated: Dec 20 '11