On 05/06/2012 03:21 AM, Chris Smith wrote:
> On Sun, May 6, 2012 at 5:05 AM, Korrignu <[email protected]> wrote:
>> Hello,
>>
>> I'm a beginner with SymPy and I need to use an indicator function which
>> returns 1 when a condition holds and 0 otherwise.
>>
>> I have this kind of stuff :
>> mu*(0<a<1)+(1-mu)*(a>1)
>>
>> when I subsitute "mu" with a value, there is no problem, but when I
>> substitute "a" there is a problem with the multiplication between an
>> integer and a boolean
>>
>> What is the good way to do ? Is there an indicator function ?
>>
> Piecewise is what you need, I think:
> Piecewise()
>
> note that you got nothing because neither condition was True. If you
> want a default value when the conditions aren't True then add that
> with the condiiton True:
>
>>>> Piecewise((mu,0<a<1),(1-mu,a>1),(42,True)).subs(a,1)
>
I tried Piecewise, and this behavior is my problem. I tried this :

  def indicator(self,condition) :
    """Returns 1 if bool 0 otherwise"""
    return Piecewise((1,type(condition)==bool and
condition),(0,type(condition)==bool and not condition), (condition, True))

to return 1 if condition holds, 0 if it doesn't hold and return
condition if condition can't be evaluated due to Symbols. So when I have
an expression build with this, there are no more piecewise function in
it, and if I do a substitution, it applies on "condition" and not on
Piecewise and it fails.

In fact, I think I need a function which is really executed as soon as
condition can be evaluated as boolean value and not before.

I home my explanation was clear.

Thx

Regards

K.

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to