# how to sum sums

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

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

( 2021-02-01 17:45:33 +0100 )edit
1

in other words, remove var from inside your functions

( 2021-02-01 18:56:39 +0100 )edit

Sort by » oldest newest most voted

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

more

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

( 2021-02-03 15:54:36 +0100 )edit