Skip to content

Commit 6e0ee05

Browse files
committed
Merge pull request sympy#8475 from skirpichev/8470-fix
Improve _needs_mul_brackets: place brackets around Mul, if it starts from "-"
2 parents 017088d + e3e11be commit 6e0ee05

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

sympy/printing/latex.py

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -194,17 +194,30 @@ def _needs_function_brackets(self, expr):
194194
else:
195195
return False
196196

197-
def _needs_mul_brackets(self, expr, last=False):
197+
def _needs_mul_brackets(self, expr, first=False, last=False):
198198
"""
199199
Returns True if the expression needs to be wrapped in brackets when
200200
printed as part of a Mul, False otherwise. This is True for Add,
201201
but also for some container objects that would not need brackets
202202
when appearing last in a Mul, e.g. an Integral. ``last=True``
203203
specifies that this expr is the last to appear in a Mul.
204+
``first=True`` specifies that this expr is the first to appear in a Mul.
204205
"""
205206
from sympy import Integral, Piecewise, Product, Sum
206-
return expr.is_Add or (not last and
207-
any([expr.has(x) for x in (Integral, Piecewise, Product, Sum)]))
207+
208+
res = False
209+
210+
if expr.is_Add:
211+
return True
212+
elif expr.is_Mul:
213+
if not first and _coeff_isneg(expr):
214+
return True
215+
216+
if (not last and
217+
any([expr.has(x) for x in (Integral, Piecewise, Product, Sum)])):
218+
return True
219+
220+
return res
208221

209222
def _mul_is_clean(self, expr):
210223
for arg in expr.args:
@@ -269,13 +282,11 @@ def _print_Float(self, expr):
269282
return str_real
270283

271284
def _print_Mul(self, expr):
272-
coeff, _ = expr.as_coeff_Mul()
273-
274-
if not coeff.is_negative:
275-
tex = ""
276-
else:
285+
if _coeff_isneg(expr):
277286
expr = -expr
278287
tex = "- "
288+
else:
289+
tex = ""
279290

280291
from sympy.simplify import fraction
281292
numer, denom = fraction(expr, exact=True)
@@ -296,7 +307,8 @@ def convert(expr):
296307
for i, term in enumerate(args):
297308
term_tex = self._print(term)
298309

299-
if self._needs_mul_brackets(term, last=(i == len(args) - 1)):
310+
if self._needs_mul_brackets(term, first=(i == 0),
311+
last=(i == len(args) - 1)):
300312
term_tex = r"\left(%s\right)" % term_tex
301313

302314
if re.search("[0-9][} ]*$", last_term_tex) and \

sympy/printing/tests/test_latex.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1301,3 +1301,9 @@ def test_issue_7180():
13011301

13021302
def test_issue_8409():
13031303
assert latex(S.Half**n) == r"\left(\frac{1}{2}\right)^{n}"
1304+
1305+
1306+
def test_issue_8470():
1307+
from sympy.parsing.sympy_parser import parse_expr
1308+
e = parse_expr("-B*A", evaluate=False)
1309+
assert latex(e) == r"A \left(- B\right)"

0 commit comments

Comments
 (0)