How to eliminate negative solutions from `sympy.solve` result?

爱⌒轻易说出口 提交于 2019-12-11 07:44:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!