[Python] Use sympy to solve constaint system with & and |

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to solve constraint systems with & and |.

    The "&" case:

    from sympy import *
    var('x', reals=True)
    formula = (x < 0) & (x < 2)
    print(solve(formula))
    # Expect: [x < 0]


    The "|" case:

    from sympy import *
    var('x', reals=True)
    formula = (x > 0) | (x < 2)
    print(solve(formula))
    # Expect: [], i.e. x \in (-\infty. +\infty)


    I know there are several workarounds, but they make the program much more complicated.

    UPD: Oscar Benjamin's answer is helpful. But I want to solve at least quadratic equations, e.g.

    from sympy import *
    var('x', reals=True)
    range = (x > 2) | (x < 0)
    equation = Eq(x ** 2 - 1, 0)
    print(simplify(equation & range))
    # Expect: [Eq(x, -1)]

    Continue reading...

Compartilhe esta Página