How to simplify sqrt expressions in sympy

I am using sympy v1.0 in a jupyter laptop . I have problems with expression to simplify as I would like. Here is an example of a toy; he does the same as my more complex expressions ...

 import sympy sympy.init_printing(use_latex='mathjax') x, y = sympy.symbols("x, y", real=True, positive=True) sympy.simplify(sqrt(2*x/y)) 

gives me ...

expression from sympy

But I would prefer ...

enter image description here

How can I get sympy to group things this way? Ive tried some of the other simplify functions, but they all give me the same result. Or am I missing something else?

+6
source share
2 answers

sympy really wants to simplify by pulling terms from sqrt , which makes sense. I think you should do what you want manually, i.e. Get the simplification you want without calling sqrt , and then release it using Symbol with the LaTex \sqrt wrapper. For instance:

 from sympy import * init_printing(use_latex='mathjax') # Wanted to show this will work for slightly more complex expressions, # but at the end it should still simplify to 2x/y x, y = symbols("x, y", real=True, positive=True) z = simplify((2*2*3*x)/(1*2*3*y)) Symbol("\sqrt{" + latex(z) + "}", real=True, positive=True) # Wrap the simplified fraction in \sqrt{} 

This is really not perfect, but I looked through the documents for about an hour and simply could not find support for what you want directly. The sympy library is more about actual symbolic manipulations, less about printing, so I can hardly blame them.

0
source

Use "cheating characters" for numbers that you want to behave like characters, and "vanilla characters" when you don't want simplifications (as @asmeurer pointed out):

 >>> _2,x,y = list(map(Symbol,'2xy')) >>> sqrt(_2*x/y) sqrt(2*x/y) 
0
source

All Articles