Search code examples
sympy

Sympy: Assume symbolic factor is positive during solve of inequality


I'm want to solve an inequality "f(x) >= y" for "x":

    from typing import Final
    import sympy as sym

    tau_S      : Final[sym.Symbol] = sym.Symbol('\\tau_\\mathrm{S}')
    tau_f      : Final[sym.Symbol] = sym.Symbol('\\tau_f')
    tau_O      : Final[sym.Symbol] = sym.Symbol('\\tau_\\mathrm{O}')
    t          : Final[sym.Symbol] = sym.Symbol('t')
    tau_on_min : Final[sym.Symbol] = sym.Symbol('\\tau_\\mathrm{on,min}')

    eq = tau_O*(-t-1)-tau_S + tau_f*t >= tau_on_min

    sym.solve(eq, t)

=>

t*(-\tau_\mathrm{O} + \tau_f) >= \tau_\mathrm{O} + \tau_\mathrm{S} + \tau_\mathrm{on,min}

Rendered: Equation

As can be seen in the screenshot which displays the equation as well as the solution, solve will not perform the division that will set "t" standing alone. Now that makes sense, given the sign of the factor is unknown.

I then tried to add an additional equation "tau_f > tau_O", to solve this, implying the factor is positive, however sympy answers with the error message:

Error message

Now I'm out of ideas, is there a way to produce the fraction for the right-hand-side that I'm interested in?


Solution

  • Change your solve line to the following and use real=True when defining t (per OScar's comment):

    >>> eps=sym.var('eps',positive=True)
    >>> sym.solve(eq.subs(tau_f,eps+tau_O), t).subs(eps,tau_f-tau_O)
    

    which gives enter image description here

    The order of the terms in a sum is determined by their sort order (and there are many questions in stackoverflow about changing the printed order of terms). If you only want to do this for display purposes, you could multiply the characters in the difference by invisible Dummy symbols that, in turn, give the desired result. YMMV:

    enter image description here