5

In Sympy, how do you isolate a generic variable?

I can do this, for instance:

>>> import sympy as sm
>>> P, rho, g, h = sm.symbols("P rho g h")
>>> depth = sm.Eq(P, rho*g*h)
>>> sm.solve(depth, h)
[P/(g*rho)]

But not this:

 >>> T, a, mu = sm.symbols("T a mu")
 >>> kepler3 = sm.Eq(T, 2*sm.pi*sm.sqrt(a**3 / mu))
 >>> solve(kepler3, a)
[2**(1/3)*(T**2*mu)**(1/3)/(2*pi**(2/3)),
 2**(1/3)*(T**2*mu)**(1/3)*(-1 + sqrt(3)*I)/(4*pi**(2/3)),
 -2**(1/3)*(T**2*mu)**(1/3)*(1 + sqrt(3)*I)/(4*pi**(2/3))]

What I'm looking for is a way to automatically generate: sm.root(mu*T**2/(4*sm.pi**2), 3), which is technically the first one of the outputs.

Solve finds the roots, though, as opposed to writing it in terms of a given variable.

Jean Nassar
  • 555
  • 1
  • 5
  • 13
  • 1
    Since it returns a list, why not point to the first index? Something like: `>>> array = solve(kepler3, a) ` and then `>>> array[0]` – Adib Apr 19 '16 at 00:21
  • `_[0]` works too. But it is only finding the roots. – Jean Nassar Apr 19 '16 at 00:22
  • I see. You want to solve in terms of 'a', correct? See if the solution here helps: http://stackoverflow.com/questions/4449110/python-solve-equation-for-one-variable – Adib Apr 19 '16 at 00:30
  • I want to find the equation in terms of a, as opposed to the roots. Implementing the linked solution gives: `[-1.27201964951407 - 1.78615137775742*I, -1.27201964951407 + 1.78615137775742*I, 1.27201964951407 - 0.213848622242577*I, 1.27201964951407 + 0.213848622242577*I]`, which are just the roots. – Jean Nassar Apr 19 '16 at 01:23
  • 3
    How do you distinguish "isolating `a`" and "finding the roots"? `a` does indeed equal the three solutions given (and as you note, they are equivalent to `root(mu*T**2/(4*sm.pi**2), 3)`). – asmeurer Apr 19 '16 at 19:24

2 Answers2

0

Perhaps you just want to use an unevaluated Power for the first solution:

>>> from sympy import S
>>> S('2**(1/3)*(T**2*mu)**(1/3)/(2*pi**(2/3))')
2**(1/3)*(T**2*mu)**(1/3)/(2*pi**(2/3))
>>> Pow(_**3,1/S(3),evaluate=False)
(T**2*mu/(4*pi**2))**(1/3)
smichr
  • 16,948
  • 2
  • 27
  • 34
0

I'have Try put the constant numbers as float.

import sympy as sm

P, rho, g, h = sm.symbols("P rho g h")
depth = sm.Eq(P, rho*g*h)
sm.solve(depth, h)

T, a, mu = sm.symbols("T a mu")
kepler3 = sm.Eq(T, 2.0*sm.pi*sm.sqrt(a**3.0 / mu))

sm.solve(kepler3, a)

out:

[0.293683865496614*(T**2*mu)**(1/3), -0.146841932748307*(T**2*mu)**(1/3) - 0.25433768820168*I*(T**2*mu)**(1/3), -0.146841932748307*(T**2*mu)**(1/3) + 0.25433768820168*I*(T**2*mu)**(1/3)]
DanSReis
  • 1
  • 2