Ask Your Question
0

Symbolic accumulation

asked 2014-06-10 02:27:50 +0100

petropolis gravatar image

updated 2014-06-12 03:49:05 +0100

With Maple I can write

seq(add(a[i], i=0..n), n=0..3);

and get

a[0], a[0]+a[1], a[0]+a[1]+a[2], a[0]+a[1]+a[2]+a[3]  (*)

If I write in Sage

for n in range(4):
    add(a[i] for i in range(n))

I get the NameError: global name 'a' is not defined. If I first introduce the variable by a = var('a') then I get the TypeError: 'sage.symbolic.expression.Expression' object does not support indexing.

How can I get the line (*) with Sage?

Edit: This works:

f=function('f')
[add(f(i) for i in (0..n)) for n in (0..3)]

gives

[f(0), f(1) + f(0), f(2) + f(1) + f(0), f(3) + f(2) + f(1) + f(0)]

So what I want is an equivalent for lists.

a=list('a')
[add(a[i] for i in (0..n)) for n in (0..3)]
edit retag flag offensive close merge delete

Comments

Is http://ask.sagemath.org/question/363/a-list-of-symbolic-variables helpful? This is unfortunately not implemented in the same way, see http://trac.sagemath.org/ticket/11576

kcrisman gravatar imagekcrisman ( 2014-06-10 12:38:39 +0100 )edit

Hmm, now I'm more confused about what you want. Lists are Python objects and of course the brackets are slicing.

kcrisman gravatar imagekcrisman ( 2014-06-12 13:14:39 +0100 )edit

2 Answers

Sort by ยป oldest newest most voted
0

answered 2014-06-18 19:34:10 +0100

slelievre gravatar image

You could define

def sums(a,nmax):
    return [sum(a[i] for i in xrange(n+1)) for n in xrange(nmax)]

Then you could compute for instance:

sage: a = [i^2 for i in xrange(20)]
sage: sums(a,10)
[0, 1, 5, 14, 30, 55, 91, 140, 204, 285]

Is that what you want, or do you want something that would take "symbolic lists" given by their names, and return a symbolic expression consisting in the formal sums of list elements? I'm not sure how one could do that.

edit flag offensive delete link more
0

answered 2014-06-14 08:36:58 +0100

niles gravatar image

Do you just want syntax to add the first k entries in a list? As @kcrisman alluded, you can get the first k entries by slicing, and then add them with

add(a[:k+1])

So you could use it like this:

sage: a = [n for n in range(5)]   # a is a list
sage: a
[0, 1, 2, 3, 4]
sage: seq = [add(a[:k+1]) for k in range(len(a))]
sage: seq
[0, 1, 3, 6, 10]

This works as long as the entries of your list can be added. Here's an example with symbolic variables:

sage: a = [var('a'+str(n)) for n in range(5)]
sage: a
[a0, a1, a2, a3, a4]
sage: seq = [add(a[:k+1]) for k in range(len(a))]
sage: seq
[a0, a0 + a1, a0 + a1 + a2, a0 + a1 + a2 + a3, a0 + a1 + a2 + a3 + a4]
edit flag offensive delete link more

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: 2014-06-10 02:27:50 +0100

Seen: 1,351 times

Last updated: Jun 18 '14