Ask Your Question
0

How to define function with indexed variables and sum

asked 2023-03-10 15:56:02 +0100

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],
f(2)=x[1]*x[2]+x[2]*x[3]
f(3)=x[1]*x[2]+x[2]*x[3]+x[3]*x[4]

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
      @cached_method
      def __getitem__(self, key):
          return SR.var("%s%s"%(self.__prefix,key))

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

Unfortunately this does not work. Any ideas?

edit retag flag offensive close merge delete

Comments

Would defining f as a Python function work for you?

f = lambda n: sum( x[k] for k in range(1,n+1) )

Max Alekseyev gravatar imageMax Alekseyev ( 2023-03-14 03:24:00 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-03-13 22:37:31 +0100

tmonteil gravatar image

updated 2023-03-13 22:38:14 +0100

Would something like the following help ?

def f(n):
    return sum(SR.var('x_{}'.format(k))*SR.var('x_{}'.format(k+1)) for k in range(1,n+1))

f(3)
x_1*x_2 + x_2*x_3 + x_3*x_4
edit flag offensive delete link more

Comments

This solution does create the necessary variables, but does not inject them in the global namespace (which can be done later with sage.misc.misc.inject_variable).

Alternatively, one can use var rather than SR.var to the same effect...

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2023-03-14 10:13:49 +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

1 follower

Stats

Asked: 2023-03-10 15:56:02 +0100

Seen: 87 times

Last updated: Mar 13 '23