SymPy: Limit symbol/variable to interval

后端 未结 4 1716
生来不讨喜
生来不讨喜 2021-01-04 08:32

Using SymPy, is it possible to limit the possible values of a symbol/variable to a certain range? I now I can set some properties while defining symbols, like positive

4条回答
  •  一生所求
    2021-01-04 09:14

    As for simplification, you want refine. Unfortunately, it doesn't yet support using inequality syntax, so you'll have to use Q.positive or Q.negative (or Q.nonpositive or Q.nonnegative for non-strict inequalities). The most common simplification that it handles is sqrt(x**2) = x if x >= 0.

    >>> refine(sqrt((x - 1)**2), Q.positive(x - 1))
    x - 1
    >>> refine(sqrt((x - 1)**2), Q.positive(x))
    Abs(x - 1)
    

    Note in the second case you still get a simpler answer because it at least knows that x - 1 is real under the given assumptions.

    If your assumptions are as simple as "x is positive" or "x is negative", the best chance for success is to define it on the Symbol itself, like

    >>> Symbol('x', positive=True)
    >>> sqrt(x**2)
    x
    

提交回复
热议问题