Sam Gue
Sam Gue

Reputation: 1

Is there a way to define an piecewise function in sympy where the intervals depend on indexed symbols?

As the title says. I have created an indexed symbol 't' and I wish to create a piecewise function that is (-1)^k when t[1]+t[2]+...+t[k]<=x<t[1]+t[2]+...+t[k]+t[k+1], up to a given maximum value of k=n. My code is currently as follows:

def SumToN(x,n):
    result = 0
    for i in range(1,n+1):
        result += x[i]
    return result

t = sp.IndexedBase('t')
x = sp.Symbol('x')
k = sp.Symbol('k')

uFunc = sp.Piecewise(((-1)^(k-1),SumToN(t,k)<=x<SumToN(t,k+1)) for k in range(1,n+1))

When I run this, I get the following error:

TypeError: cannot determine truth value of Relational

I understand that it is having trouble with being able to confirm which region x is in, but when I try this with say 3 symbols t1, t2, and t3, I get no errors. Am I doing something clearly wrong, and is there a way to do this?

Upvotes: 0

Views: 256

Answers (1)

smichr
smichr

Reputation: 19057

You cannot create a compound inequality with symbols, only numbers. So 1<2<3 works but 1<Symbol('x')<3 must be written as x = Symbol('x'); And(1 < x, x < 3). Also, Piecewise does not work with an iterator, so try:

Piecewise(*[((-1)^(k-1), And(SumToN(t,k)<=x, x<SumToN(t,k+1)))
 for k in range(1,n+1)])

Upvotes: 1

Related Questions