i2_
i2_

Reputation: 735

SymPy : Indexed symbols to Summation

I have an expression like:

-(a[1]*b[1] + a[2]*b[2])/((a[1]*b[1] - a[1] + a[2]*b[2] - a[2])) 

and turn it

(-summation(b[omega]*a[omega]))/(summation((b[omega]-1)*a[omega]))

where

omega = 1,2 

is it possible?

Upvotes: 0

Views: 89

Answers (1)

Chris du Plessis
Chris du Plessis

Reputation: 1370

A Python loop is probably simpler than what you're trying to do.

Something like

numerator = -sum([b[omega]*a[omega] for omega in range(len(a))])
denominator = sum([(b[omega]-1)*a[omega] for omega in range(len(a))])
result = numerator/denominator

If you want something based more around SymPy you'll have to get more involved since Python does not accept symbols when indexing arrays. There are probably many ways to do this but this was the first one that came to mind:

from sympy import *
omega = symbols('omega')
a = symbols('a1 a2')
b = symbols('b1 b2')

class A(Function):
    @classmethod
    def eval(self, x):
        if isinstance(x, Symbol):
            return
        else:
            return a[x]

class B(Function):
    @classmethod
    def eval(self, x):
        if isinstance(x, Symbol):
            return
        else:
            return b[x]

# indexing starts at 0
numerator = -summation(B(omega)*A(omega), (omega, 0, 1))
denominator = summation((B(omega)-1)*A(omega), (omega, 0, 1))
result = numerator/denominator 

Upvotes: 1

Related Questions