Reputation: 733
I am having the very same problem asked in this question, but I can't figure out why the solution is not working.
In that question, there was an issue in sqrt
function that seems to be solved, and now that problem leads to only positive results.
But in my problem, I can't eliminate the negative solution in the following code:
import sympy
v,Vs,Vp = sympy.symbols('v,Vs,Vp',real=True,positive=True)
sympy.solve( v - (Vp**2-2*Vs**2)/(2*(Vp**2-Vs**2)), Vs)
Which gives me the result
[-sqrt(2)*Vp*sqrt((2*v - 1)/(v - 1))/2, sqrt(2)*Vp*sqrt((2*v - 1)/(v - 1))/2]
How can I get only the positive result? What am I missing?
Upvotes: 1
Views: 715
Reputation: 1370
As the comments in the thread already describe, it is not really possible to get what you want in general.
There is a trick to assume 0 < v < 1/2
. Since this involves a few fractions, intuition says that we should probably make a substitution that involves a fraction too.
import sympy
Vs,Vp = sympy.symbols('Vs,Vp', positive=True)
# A hack to assume 0 < v < 1/2
u = sympy.symbols('u', positive=True)
v = 1/(u+2) # Alternatives like atan can be used when there are trig functions
sol = sympy.solve( v - (Vp**2-2*Vs**2)/(2*(Vp**2-Vs**2)), Vs)
print(sol)
# Substitute back by redefining v
v = sympy.symbols('v', positive=True)
new_sol = [subsol.subs(u, 1/v - 2).simplify() for subsol in sol]
print(new_sol)
The next best you can do in this case is assume all square roots are positive which is a very brave assumption.
import sympy
v,Vs,Vp = sympy.symbols('v,Vs,Vp', real=True, positive=True)
sol = sympy.solve( v - (Vp**2-2*Vs**2)/(2*(Vp**2-Vs**2)), Vs)
# Assume sqrts are positive and sol is an array
# Both of these are not true in general
# It does not work if we assume the square root can be zero
# Or even complex or negative
s = sympy.symbols('s', positive=True) # Represents any square root
w = sympy.Wild('w') # Represents any argument inside a square root
new_sol = [subsol for subsol in sol if subsol.replace(sympy.sqrt(w), s) > 0]
print(new_sol)
Both code blocks assume sol
is an array which is not true in general when it comes to solve
.
Upvotes: 4