Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...