Ask Your Question

Revision history [back]

How to define function with indexed variables and sum

I would like to define a function f(n)=sum(x[k]*x[k+1], k= 1..n) so that it produces expressions like this:

f(1)= x[1]*x[2],

How to do this in sage? I tried to generate indexed variable with the following:

class VariableGenerator(object):
      def __init__(self, prefix):
          self.__prefix = prefix
      def __getitem__(self, key):
          return SR.var("%s%s"%(self.__prefix,key))

k, n = var('k,n')
f(n)=sum(x[k], k, 1, n)

Unfortunately this does not work. Any ideas?