问题
How can I make sympy.solve
not return negative solutions?
This seems to be a different task than adding a constraint like positive=True
to the symbol I'm solving for. While
import sympy
x = sympy.symbols("x")
print(sympy.solve(x**2-4, x))
x = sympy.symbols("x", positive=True)
print(sympy.solve(x**2-4, x))
prints
[-2, 2]
[2]
as expected - I still get a negative solve result for omega
with
import sympy
omega, omega_0, gamma = sympy.symbols("omega, omega_0, gamma", real=True, positive=True)
zeta = 1/((omega_0**2 - omega**2)**2 + gamma**2*omega**2)
omega_R = sympy.solve(sympy.diff(zeta, omega), omega)
print(omega_R)
which returns
[-sqrt(2)*sqrt(-gamma**2 + 2*omega_0**2)/2, sqrt(2)*sqrt(-gamma**2 + 2*omega_0**2)/2]
even though -sqrt(2)*sqrt(-gamma**2 + 2*omega_0**2)/2
will never be positive for real and positive symbols omega_0
and gamma
.
Alternatively, whats's the best way to eliminate the negative solutions afterwards?
回答1:
SymPy's assumptions system isn't smart enough to know that -sqrt(2)*sqrt(-gamma**2 + 2*omega_0**2)/2
cannot be positive give the real
and positive
assumptions on omega_0
and gamma
(I opened an issue for it). To be on the safe side, SymPy only filters solutions if it knows they cannot have the given assumptions. If the assumptions system gives None
, meaning it doesn't know, it includes it anyway. For now your best bet is to just filter this solution manually.
来源:https://stackoverflow.com/questions/50476889/how-to-eliminate-negative-solutions-from-sympy-solve-result