Sergey
Sergey

Reputation: 1328

Sympy does not simplify an expression with a symbol divided by the square root of its square

I have a problem with sympy simplification. See the code below. When I substitute expression under sqrt with something, it becomes "unbreakable". For example, in the last line of code I multiplied expression by f0 and simplified the result. f0 in numerator and sqrt(f0**2) in denominator did not get simplified out even though f0 is declared as nonnegative. What did I do wrong and how do I substitute expressions without having this effect?

Code (pretty version with rendered equations):

>>> from __future__ import division
>>> from sympy import *
>>> from sympy.abc import pi

>>> init_printing(use_unicode=True)
>>> L0, Csum0, f0 = symbols("L0 C_{{\\Sigma}0} f0", nonnegative=True)
>>> equation = sqrt(L0)
>>> equation
  ____
╲╱ L₀

>>> substitute = solve(Eq(1/(2*pi*sqrt(L0)*sqrt(Csum0)), f0), L0, dict=1)[0]
>>> substitute
⎧              1           ⎫
⎪L₀: ──────────────────────⎪
⎨                      2  2⎬
⎪    4⋅C_{{\Sigma}0}⋅f₀ ⋅π ⎪
⎩                          ⎭

>>> equation = equation.subs(substitute)
>>> equation
     ______________________
    ╱          1
   ╱  ────────────────────
  ╱                   2  2
╲╱    C_{{\Sigma}0}⋅f₀ ⋅π
───────────────────────────
             2

>>> simplify(equation*f0)
        ______________________
       ╱          1
f₀⋅   ╱  ────────────────────
     ╱                   2  2
   ╲╱    C_{{\Sigma}0}⋅f₀ ⋅π
──────────────────────────────
               2

Upvotes: 3

Views: 1896

Answers (1)

user6655984
user6655984

Reputation:

Cancelling f0/sqrt(f0**2) is not legitimate when f0 is 0. To ensure this cancellation is allowed, declare f0 to be positive, not just nonnegative.

Also, importing pi from sympy.abc makes pi a generic symbol with no specific meaning; in particular, it's not known to be positive. SymPy already has pi (mathematical constant) built-in, and knows it's a positive number. So removing the import from sympy.abc improves simplification.

from sympy import *
L0, Csum0, f0 = symbols("L0 C_{{\\Sigma}0} f0", positive=True)
equation = sqrt(L0)
substitute = solve(Eq(1/(2*pi*sqrt(L0)*sqrt(Csum0)), f0), L0, dict=1)[0]
equation = equation.subs(substitute)
simplify(equation*f0)

returns

1/(2*pi*sqrt(C_{{\Sigma}0}))

Upvotes: 2

Related Questions