Ask Your Question
1

how to sum sums

asked 2021-02-01 09:49:00 +0100

smokzeta gravatar image

updated 2021-02-03 02:36:09 +0100

slelievre gravatar image

I am new to sagemath and I am trying to calculate some formulas using it.

I learned how to write a sum such as

sage: a = [2, 2, 3, 4] 
sage: d = [2, 4, 5, 6] 
sage: def pi(i): 
....:      var("i")
....:      f = sum([a[k]*d[k] for k in range(i + 1)])
....:      return f

However, I am having difficulties to write a sum for pi(i) such as

sage: def Z(a, b): 
....:      var("a b")
....:      l = len(d) - 1 
....:      def pi(i):
....:          var("i")
....:          f = sum([a[k]*d[k] for k in range(i + 1)])
....:          return f
....:      h = sum([pi(i) for i in range(l - 1)])
....:      return h

but I got error. I tried to use

for i in range(l - 1):

also it doesn't work.

edit retag flag offensive close merge delete

Comments

1

As a first step, redefining new (local) symbolic variable(s) with the same name(s) as your function parameters forbids access to the latter, hence your errors...

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2021-02-01 17:45:33 +0100 )edit
1

in other words, remove var from inside your functions

FrédéricC gravatar imageFrédéricC ( 2021-02-01 18:56:39 +0100 )edit

1 Answer

Sort by » oldest newest most voted
0

answered 2021-02-03 02:45:31 +0100

slelievre gravatar image

Besides the suggestion by @Emmanuel Charpentier and @FrédéricC ...

... it seems you are trying to reimplement the dot product of vectors.

Python provides more efficient ways to sum elementwise products of lists.

Sage also has a built-in dot product for vectors.

With a and d defined as lists:

sage: a = [2, 2, 3, 4]
sage: d = [2, 4, 5, 6]

Python:

sage: sum(ak * dk for ak, dk in zip(a, d))
51

Sage:

sage: vector(a) * vector(d)
51

With a and d defined directly as vectors:

sage: a = vector([2, 2, 3, 4])
sage: d = vector([2, 4, 5, 6])
sage: a * d
51
edit flag offensive delete link more

Comments

Just for completeness, if a and d are vectors, one can also write a.dot_product(d).

Juanjo gravatar imageJuanjo ( 2021-02-03 15:54:36 +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

Stats

Asked: 2021-02-01 09:49:00 +0100

Seen: 948 times

Last updated: Feb 03 '21