BlankSeed
BlankSeed

Reputation: 66

how to represent a variable with other variables given a equation set in SymPy?

I tried to eliminate r and z from the equation set and get the expression of S without r and z:

enter image description here

var('xi R R_bfs k S z r')
solve(r**2 - 2*R*z + (k + 1)*z**2, S*cos(xi)+z-R_bfs, S*sin(xi)-r, S, r, z)

This returns an empty list for S, but I am sure there is solution for s. Is there any method or function to handle this problem?

Upvotes: 1

Views: 408

Answers (1)

smichr
smichr

Reputation: 18939

When I run into problems like this I try to use the CAS to do the steps for me that lead to the solution that I want. With only 3 equations this is pretty straightforward.

We can eliminate S from the last 2 equations

>>> eqs = r**2 - 2*R*z + (k + 1)*z**2, S*cos(xi)+z-R_bfs, S*sin(xi)-r
>>> solve(eqs[1:],(r,z))
{r: S*sin(xi), z: R_bfs - S*cos(xi)}

This solution can be substituted into the first equation

>>> e1 = eqs[0].subs(_)

This results in a polynomial in S, of degree = 2, that does not contain r or z

>>> degree(e1, S)
2
>>> e1.has(r, z)
False

And the solutions of a general quadratic are

>>> q = solve(a*x**2 + b*x + c, x); q
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]

So all we need are the values of a, b and c from e1 and we should have our solutions for S, free or r and z:

>>> A, B, C = Poly(e1, S).all_coeffs()
>>> solns = [i.subs({a: A, b: B, c: C}) for i in q]

Before we look at those, let's let cse remove common expressions

>>> reps, sols = cse(solns)

Here are the replacements that are identified

>>> for i in reps:
...     print(i)
(x0, cos(xi))
(x1, x0**2)
(x2, k*x1 + x1 + sin(xi)**2)
(x3, 1/(2*x2))
(x4, 2*R)
(x5, x0*x4)
(x6, 2*R_bfs*x0)
(x7, k*x6)
(x8, x5 - x6 - x7)
(x9, R_bfs**2)
(x10, sqrt(-4*x2*(-R_bfs*x4 + k*x9 + x9) + x8**2))

And in terms of those, here are the solutions:

>>> for i in sols:
...     print(i)
x3*(x10 - x5 + x6 + x7)
-x3*(x10 + x8)

If you prefer the non-cse form, you can look at that, too. Here is one solution:

>>> print(filldedent(solns[0]))

(-2*R*cos(xi) + 2*R_bfs*k*cos(xi) + 2*R_bfs*cos(xi) +
sqrt(-4*(-2*R*R_bfs + R_bfs**2*k + R_bfs**2)*(k*cos(xi)**2 +
sin(xi)**2 + cos(xi)**2) + (2*R*cos(xi) - 2*R_bfs*k*cos(xi) -
2*R_bfs*cos(xi))**2))/(2*(k*cos(xi)**2 + sin(xi)**2 + cos(xi)**2))

If your initial all-in-one-go solution fails, try to let SymPy be your Swiss Army Knife :-)

Upvotes: 1

Related Questions