@@ -194,17 +194,30 @@ def _needs_function_brackets(self, expr):
194
194
else :
195
195
return False
196
196
197
- def _needs_mul_brackets (self , expr , last = False ):
197
+ def _needs_mul_brackets (self , expr , first = False , last = False ):
198
198
"""
199
199
Returns True if the expression needs to be wrapped in brackets when
200
200
printed as part of a Mul, False otherwise. This is True for Add,
201
201
but also for some container objects that would not need brackets
202
202
when appearing last in a Mul, e.g. an Integral. ``last=True``
203
203
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.
204
205
"""
205
206
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
208
221
209
222
def _mul_is_clean (self , expr ):
210
223
for arg in expr .args :
@@ -269,13 +282,11 @@ def _print_Float(self, expr):
269
282
return str_real
270
283
271
284
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 ):
277
286
expr = - expr
278
287
tex = "- "
288
+ else :
289
+ tex = ""
279
290
280
291
from sympy .simplify import fraction
281
292
numer , denom = fraction (expr , exact = True )
@@ -296,7 +307,8 @@ def convert(expr):
296
307
for i , term in enumerate (args ):
297
308
term_tex = self ._print (term )
298
309
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 )):
300
312
term_tex = r"\left(%s\right)" % term_tex
301
313
302
314
if re .search ("[0-9][} ]*$" , last_term_tex ) and \
0 commit comments