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?

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
  • 3
    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). – asmeurer Apr 23 '16 at 16:53
  • @asmeurer 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. – Matt Hall Apr 25 '16 at 23:40

2 Answers2

1

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)
smichr
  • 16,948
  • 2
  • 27
  • 34
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.

Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52
  • I appreciate your insight, but this feels too complicated. The suggestion of not specifying real, positive symbols helped me. Thank you anyway. – Matt Hall Apr 25 '16 at 23:38