How to simplify sqrt expressions in sympy
Asked Answered
B

2

6

I'm using sympy v1.0 in a Jupyter Notebook. I'm having trouble getting expression to simplify how I'd like. Here's a toy example; it does the same thing my more complicated expressions do...

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 in this way? Ive tried some of the other simplify functions, but they all give me the same result. Or am I missing something else?

Bonar answered 22/4, 2016 at 16:13 Comment(2)
If you don't set x and y as real and positive, SymPy won't split them apart (because it's invalid to do so).Stag
@Stag Thank you this does indeed help. It still pulls the 2 out, but that's easier to deal with. I found I can also improvise by squaring everything to check how it gathers everything.Bonar
W
2

Use "symbol trickery" for numbers that you want to behave like symbols and "vanilla symbols" 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)
Waine answered 7/7, 2019 at 18:41 Comment(4)
Thanks! This feels like a workaround too, but a bit more workable than the other answer, so I'll accept it. Cheers.Bonar
Thank you. And yes, it's just one of several ways to work around this issue.Waine
For me, the assumption positive=True on the symbols still breaks out the terms of the sqrt Any solution for this?Evante
Don't make the symbols positive or else use evaluate=False as in sqrt(2*x, evaluate=False).Waine
B
0

sympy really wants to simplify by pulling terms out of sqrt, which makes sense. I think you have to do what you want manually, i.e., get the simplification you want without the sqrt call, and then fudge it using Symbol with a LaTex \sqrt wrap. For example:

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 really isn't ideal, but I looked through the docs for about an hour, and just couldn't find support for what you want directly. The sympy library is more about actual symbolic manipulation, less about printing, so I can hardly blame them.

Bialystok answered 22/4, 2016 at 18:5 Comment(1)
I appreciate your insight, but this feels too complicated. The suggestion of not specifying real, positive symbols helped me. Thank you anyway.Bonar

© 2022 - 2024 — McMap. All rights reserved.