Search code examples
pythonsympy

Basic algebra with sympy: keep coefficients and variables together


I'm trying to use sympy for some basic algebra and physics. When defining an equation such as

import sympy as sy
g,h = sy.Symbols("g h")
v = sy.sqrt(2 * g * h)

the equation v gets expanded to

v = sqrt(2) * sqrt(g * h)

there a way to specify that the coefficient "2" should not be factored out from under the square root and the term under the sqare root is kept as "2 * g * h"? The reason I want to do this is that the underlying physics and the derivation of a resulting equation are sometimes much clearer to see if the relevant coefficients are not factored out.

Another example would be something like calculating the arc lenght in an equation like

phi = sy.symbols("phi")
r = sy.symbols("r")
a= r * phi

for the double of an angle

phi = sy.pi / 4

as in

a = r * (2 * phi)

which gets collected to

a = r * sy.pi / 2

when

a = r *  2 * (sy.pi / 4)

might be clearer to show how the result was obtained.


Solution

  • is there a way to specify that the coefficient "2" should not be factored out from under the square root and the term under the sqare root is kept as "2 * g * h"?

    Yes, just create a Pow object (power raise) with the optional parameter evaluate=False:

    >>> Pow(2*g*h, S(1)/2, evaluate=False)
      _______
    \/ 2*g*h 
    

    That is, 2*g*h gets raised by S(1)/2 (one half). Automatic evaluation during the object construction is disabled by evaluate=False.