pythonpython-3.xsympy

Error when trying to apply a conditional statement to sympy


I'm trying to set a conditional statmeent in sympy so that when the iterable is not equal to a certain number (30) in this case, it returns 0.

My code is:

def formula(address):

    address0 = 30
    logic = 3 * x

    # Define the symbol and the summation range
    x = symbols('x')

    expr = Piecewise(
        (x + logic, logic == address0),  # When x equals certain_integer, only add logic
        ((x + logic) - (x + logic), logic!=address0) # For all other values of x, apply full logic (x + logic - x + logic)
    )

    #If -x + logic only do it to the ones that aren't address0
    total = summation(expr(x, 0, 089237316195423570985008687907836))
    total2 = total - address0
    print(f'{total}\n{total2}')
    return total2

As you can see in my code, in the expr variable I set x+logic when logic is 30 and when the other logicsaren't 30 it returns 0 since it subtracts it. The code is returning 0 regardless of what I do and I don't know why. Can someone help me?


Solution

  • The == operator will instantly evaluate to True or False based on structure of the objects. Since 3*x is not 30 the equality evaluates to False and that term of the Piecewise is ignored. Use the following instead:

    ...
    from sympy import Eq
    expr = Piecewise(
            (x + logic, Eq(logic,address0)),
            (0, True)) # (x+logic)-(x-logic)->0 if x and logic are finite
    

    Your use of summation seems strange, too. How about:

    >>> piecewise_fold(Sum(expr,(x,0,100))).doit()
    Piecewise((20200, Eq(x, 10)), (0, True))
    

    But I am not really sure what you are trying to do with summation.