radsimp.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. from collections import defaultdict
  2. from sympy.core import sympify, S, Mul, Derivative, Pow
  3. from sympy.core.add import _unevaluated_Add, Add
  4. from sympy.core.assumptions import assumptions
  5. from sympy.core.exprtools import Factors, gcd_terms
  6. from sympy.core.function import _mexpand, expand_mul, expand_power_base
  7. from sympy.core.mul import _keep_coeff, _unevaluated_Mul, _mulsort
  8. from sympy.core.numbers import Rational, zoo, nan
  9. from sympy.core.parameters import global_parameters
  10. from sympy.core.sorting import ordered, default_sort_key
  11. from sympy.core.symbol import Dummy, Wild, symbols
  12. from sympy.functions import exp, sqrt, log
  13. from sympy.functions.elementary.complexes import Abs
  14. from sympy.polys import gcd
  15. from sympy.simplify.sqrtdenest import sqrtdenest
  16. from sympy.utilities.iterables import iterable, sift
  17. def collect(expr, syms, func=None, evaluate=None, exact=False, distribute_order_term=True):
  18. """
  19. Collect additive terms of an expression.
  20. Explanation
  21. ===========
  22. This function collects additive terms of an expression with respect
  23. to a list of expression up to powers with rational exponents. By the
  24. term symbol here are meant arbitrary expressions, which can contain
  25. powers, products, sums etc. In other words symbol is a pattern which
  26. will be searched for in the expression's terms.
  27. The input expression is not expanded by :func:`collect`, so user is
  28. expected to provide an expression in an appropriate form. This makes
  29. :func:`collect` more predictable as there is no magic happening behind the
  30. scenes. However, it is important to note, that powers of products are
  31. converted to products of powers using the :func:`~.expand_power_base`
  32. function.
  33. There are two possible types of output. First, if ``evaluate`` flag is
  34. set, this function will return an expression with collected terms or
  35. else it will return a dictionary with expressions up to rational powers
  36. as keys and collected coefficients as values.
  37. Examples
  38. ========
  39. >>> from sympy import S, collect, expand, factor, Wild
  40. >>> from sympy.abc import a, b, c, x, y
  41. This function can collect symbolic coefficients in polynomials or
  42. rational expressions. It will manage to find all integer or rational
  43. powers of collection variable::
  44. >>> collect(a*x**2 + b*x**2 + a*x - b*x + c, x)
  45. c + x**2*(a + b) + x*(a - b)
  46. The same result can be achieved in dictionary form::
  47. >>> d = collect(a*x**2 + b*x**2 + a*x - b*x + c, x, evaluate=False)
  48. >>> d[x**2]
  49. a + b
  50. >>> d[x]
  51. a - b
  52. >>> d[S.One]
  53. c
  54. You can also work with multivariate polynomials. However, remember that
  55. this function is greedy so it will care only about a single symbol at time,
  56. in specification order::
  57. >>> collect(x**2 + y*x**2 + x*y + y + a*y, [x, y])
  58. x**2*(y + 1) + x*y + y*(a + 1)
  59. Also more complicated expressions can be used as patterns::
  60. >>> from sympy import sin, log
  61. >>> collect(a*sin(2*x) + b*sin(2*x), sin(2*x))
  62. (a + b)*sin(2*x)
  63. >>> collect(a*x*log(x) + b*(x*log(x)), x*log(x))
  64. x*(a + b)*log(x)
  65. You can use wildcards in the pattern::
  66. >>> w = Wild('w1')
  67. >>> collect(a*x**y - b*x**y, w**y)
  68. x**y*(a - b)
  69. It is also possible to work with symbolic powers, although it has more
  70. complicated behavior, because in this case power's base and symbolic part
  71. of the exponent are treated as a single symbol::
  72. >>> collect(a*x**c + b*x**c, x)
  73. a*x**c + b*x**c
  74. >>> collect(a*x**c + b*x**c, x**c)
  75. x**c*(a + b)
  76. However if you incorporate rationals to the exponents, then you will get
  77. well known behavior::
  78. >>> collect(a*x**(2*c) + b*x**(2*c), x**c)
  79. x**(2*c)*(a + b)
  80. Note also that all previously stated facts about :func:`collect` function
  81. apply to the exponential function, so you can get::
  82. >>> from sympy import exp
  83. >>> collect(a*exp(2*x) + b*exp(2*x), exp(x))
  84. (a + b)*exp(2*x)
  85. If you are interested only in collecting specific powers of some symbols
  86. then set ``exact`` flag to True::
  87. >>> collect(a*x**7 + b*x**7, x, exact=True)
  88. a*x**7 + b*x**7
  89. >>> collect(a*x**7 + b*x**7, x**7, exact=True)
  90. x**7*(a + b)
  91. If you want to collect on any object containing symbols, set
  92. ``exact`` to None:
  93. >>> collect(x*exp(x) + sin(x)*y + sin(x)*2 + 3*x, x, exact=None)
  94. x*exp(x) + 3*x + (y + 2)*sin(x)
  95. >>> collect(a*x*y + x*y + b*x + x, [x, y], exact=None)
  96. x*y*(a + 1) + x*(b + 1)
  97. You can also apply this function to differential equations, where
  98. derivatives of arbitrary order can be collected. Note that if you
  99. collect with respect to a function or a derivative of a function, all
  100. derivatives of that function will also be collected. Use
  101. ``exact=True`` to prevent this from happening::
  102. >>> from sympy import Derivative as D, collect, Function
  103. >>> f = Function('f') (x)
  104. >>> collect(a*D(f,x) + b*D(f,x), D(f,x))
  105. (a + b)*Derivative(f(x), x)
  106. >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), f)
  107. (a + b)*Derivative(f(x), (x, 2))
  108. >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), D(f,x), exact=True)
  109. a*Derivative(f(x), (x, 2)) + b*Derivative(f(x), (x, 2))
  110. >>> collect(a*D(f,x) + b*D(f,x) + a*f + b*f, f)
  111. (a + b)*f(x) + (a + b)*Derivative(f(x), x)
  112. Or you can even match both derivative order and exponent at the same time::
  113. >>> collect(a*D(D(f,x),x)**2 + b*D(D(f,x),x)**2, D(f,x))
  114. (a + b)*Derivative(f(x), (x, 2))**2
  115. Finally, you can apply a function to each of the collected coefficients.
  116. For example you can factorize symbolic coefficients of polynomial::
  117. >>> f = expand((x + a + 1)**3)
  118. >>> collect(f, x, factor)
  119. x**3 + 3*x**2*(a + 1) + 3*x*(a + 1)**2 + (a + 1)**3
  120. .. note:: Arguments are expected to be in expanded form, so you might have
  121. to call :func:`~.expand` prior to calling this function.
  122. See Also
  123. ========
  124. collect_const, collect_sqrt, rcollect
  125. """
  126. expr = sympify(expr)
  127. syms = [sympify(i) for i in (syms if iterable(syms) else [syms])]
  128. # replace syms[i] if it is not x, -x or has Wild symbols
  129. cond = lambda x: x.is_Symbol or (-x).is_Symbol or bool(
  130. x.atoms(Wild))
  131. _, nonsyms = sift(syms, cond, binary=True)
  132. if nonsyms:
  133. reps = dict(zip(nonsyms, [Dummy(**assumptions(i)) for i in nonsyms]))
  134. syms = [reps.get(s, s) for s in syms]
  135. rv = collect(expr.subs(reps), syms,
  136. func=func, evaluate=evaluate, exact=exact,
  137. distribute_order_term=distribute_order_term)
  138. urep = {v: k for k, v in reps.items()}
  139. if not isinstance(rv, dict):
  140. return rv.xreplace(urep)
  141. else:
  142. return {urep.get(k, k).xreplace(urep): v.xreplace(urep)
  143. for k, v in rv.items()}
  144. # see if other expressions should be considered
  145. if exact is None:
  146. _syms = set()
  147. for i in Add.make_args(expr):
  148. if not i.has_free(*syms) or i in syms:
  149. continue
  150. if not i.is_Mul and i not in syms:
  151. _syms.add(i)
  152. else:
  153. # identify compound generators
  154. g = i._new_rawargs(*i.as_coeff_mul(*syms)[1])
  155. if g not in syms:
  156. _syms.add(g)
  157. simple = all(i.is_Pow and i.base in syms for i in _syms)
  158. syms = syms + list(ordered(_syms))
  159. if not simple:
  160. return collect(expr, syms,
  161. func=func, evaluate=evaluate, exact=False,
  162. distribute_order_term=distribute_order_term)
  163. if evaluate is None:
  164. evaluate = global_parameters.evaluate
  165. def make_expression(terms):
  166. product = []
  167. for term, rat, sym, deriv in terms:
  168. if deriv is not None:
  169. var, order = deriv
  170. for _ in range(order):
  171. term = Derivative(term, var)
  172. if sym is None:
  173. if rat is S.One:
  174. product.append(term)
  175. else:
  176. product.append(Pow(term, rat))
  177. else:
  178. product.append(Pow(term, rat*sym))
  179. return Mul(*product)
  180. def parse_derivative(deriv):
  181. # scan derivatives tower in the input expression and return
  182. # underlying function and maximal differentiation order
  183. expr, sym, order = deriv.expr, deriv.variables[0], 1
  184. for s in deriv.variables[1:]:
  185. if s == sym:
  186. order += 1
  187. else:
  188. raise NotImplementedError(
  189. 'Improve MV Derivative support in collect')
  190. while isinstance(expr, Derivative):
  191. s0 = expr.variables[0]
  192. if any(s != s0 for s in expr.variables):
  193. raise NotImplementedError(
  194. 'Improve MV Derivative support in collect')
  195. if s0 == sym:
  196. expr, order = expr.expr, order + len(expr.variables)
  197. else:
  198. break
  199. return expr, (sym, Rational(order))
  200. def parse_term(expr):
  201. """Parses expression expr and outputs tuple (sexpr, rat_expo,
  202. sym_expo, deriv)
  203. where:
  204. - sexpr is the base expression
  205. - rat_expo is the rational exponent that sexpr is raised to
  206. - sym_expo is the symbolic exponent that sexpr is raised to
  207. - deriv contains the derivatives of the expression
  208. For example, the output of x would be (x, 1, None, None)
  209. the output of 2**x would be (2, 1, x, None).
  210. """
  211. rat_expo, sym_expo = S.One, None
  212. sexpr, deriv = expr, None
  213. if expr.is_Pow:
  214. if isinstance(expr.base, Derivative):
  215. sexpr, deriv = parse_derivative(expr.base)
  216. else:
  217. sexpr = expr.base
  218. if expr.base == S.Exp1:
  219. arg = expr.exp
  220. if arg.is_Rational:
  221. sexpr, rat_expo = S.Exp1, arg
  222. elif arg.is_Mul:
  223. coeff, tail = arg.as_coeff_Mul(rational=True)
  224. sexpr, rat_expo = exp(tail), coeff
  225. elif expr.exp.is_Number:
  226. rat_expo = expr.exp
  227. else:
  228. coeff, tail = expr.exp.as_coeff_Mul()
  229. if coeff.is_Number:
  230. rat_expo, sym_expo = coeff, tail
  231. else:
  232. sym_expo = expr.exp
  233. elif isinstance(expr, exp):
  234. arg = expr.exp
  235. if arg.is_Rational:
  236. sexpr, rat_expo = S.Exp1, arg
  237. elif arg.is_Mul:
  238. coeff, tail = arg.as_coeff_Mul(rational=True)
  239. sexpr, rat_expo = exp(tail), coeff
  240. elif isinstance(expr, Derivative):
  241. sexpr, deriv = parse_derivative(expr)
  242. return sexpr, rat_expo, sym_expo, deriv
  243. def parse_expression(terms, pattern):
  244. """Parse terms searching for a pattern.
  245. Terms is a list of tuples as returned by parse_terms;
  246. Pattern is an expression treated as a product of factors.
  247. """
  248. pattern = Mul.make_args(pattern)
  249. if len(terms) < len(pattern):
  250. # pattern is longer than matched product
  251. # so no chance for positive parsing result
  252. return None
  253. else:
  254. pattern = [parse_term(elem) for elem in pattern]
  255. terms = terms[:] # need a copy
  256. elems, common_expo, has_deriv = [], None, False
  257. for elem, e_rat, e_sym, e_ord in pattern:
  258. if elem.is_Number and e_rat == 1 and e_sym is None:
  259. # a constant is a match for everything
  260. continue
  261. for j in range(len(terms)):
  262. if terms[j] is None:
  263. continue
  264. term, t_rat, t_sym, t_ord = terms[j]
  265. # keeping track of whether one of the terms had
  266. # a derivative or not as this will require rebuilding
  267. # the expression later
  268. if t_ord is not None:
  269. has_deriv = True
  270. if (term.match(elem) is not None and
  271. (t_sym == e_sym or t_sym is not None and
  272. e_sym is not None and
  273. t_sym.match(e_sym) is not None)):
  274. if exact is False:
  275. # we don't have to be exact so find common exponent
  276. # for both expression's term and pattern's element
  277. expo = t_rat / e_rat
  278. if common_expo is None:
  279. # first time
  280. common_expo = expo
  281. else:
  282. # common exponent was negotiated before so
  283. # there is no chance for a pattern match unless
  284. # common and current exponents are equal
  285. if common_expo != expo:
  286. common_expo = 1
  287. else:
  288. # we ought to be exact so all fields of
  289. # interest must match in every details
  290. if e_rat != t_rat or e_ord != t_ord:
  291. continue
  292. # found common term so remove it from the expression
  293. # and try to match next element in the pattern
  294. elems.append(terms[j])
  295. terms[j] = None
  296. break
  297. else:
  298. # pattern element not found
  299. return None
  300. return [_f for _f in terms if _f], elems, common_expo, has_deriv
  301. if evaluate:
  302. if expr.is_Add:
  303. o = expr.getO() or 0
  304. expr = expr.func(*[
  305. collect(a, syms, func, True, exact, distribute_order_term)
  306. for a in expr.args if a != o]) + o
  307. elif expr.is_Mul:
  308. return expr.func(*[
  309. collect(term, syms, func, True, exact, distribute_order_term)
  310. for term in expr.args])
  311. elif expr.is_Pow:
  312. b = collect(
  313. expr.base, syms, func, True, exact, distribute_order_term)
  314. return Pow(b, expr.exp)
  315. syms = [expand_power_base(i, deep=False) for i in syms]
  316. order_term = None
  317. if distribute_order_term:
  318. order_term = expr.getO()
  319. if order_term is not None:
  320. if order_term.has(*syms):
  321. order_term = None
  322. else:
  323. expr = expr.removeO()
  324. summa = [expand_power_base(i, deep=False) for i in Add.make_args(expr)]
  325. collected, disliked = defaultdict(list), S.Zero
  326. for product in summa:
  327. c, nc = product.args_cnc(split_1=False)
  328. args = list(ordered(c)) + nc
  329. terms = [parse_term(i) for i in args]
  330. small_first = True
  331. for symbol in syms:
  332. if isinstance(symbol, Derivative) and small_first:
  333. terms = list(reversed(terms))
  334. small_first = not small_first
  335. result = parse_expression(terms, symbol)
  336. if result is not None:
  337. if not symbol.is_commutative:
  338. raise AttributeError("Can not collect noncommutative symbol")
  339. terms, elems, common_expo, has_deriv = result
  340. # when there was derivative in current pattern we
  341. # will need to rebuild its expression from scratch
  342. if not has_deriv:
  343. margs = []
  344. for elem in elems:
  345. if elem[2] is None:
  346. e = elem[1]
  347. else:
  348. e = elem[1]*elem[2]
  349. margs.append(Pow(elem[0], e))
  350. index = Mul(*margs)
  351. else:
  352. index = make_expression(elems)
  353. terms = expand_power_base(make_expression(terms), deep=False)
  354. index = expand_power_base(index, deep=False)
  355. collected[index].append(terms)
  356. break
  357. else:
  358. # none of the patterns matched
  359. disliked += product
  360. # add terms now for each key
  361. collected = {k: Add(*v) for k, v in collected.items()}
  362. if disliked is not S.Zero:
  363. collected[S.One] = disliked
  364. if order_term is not None:
  365. for key, val in collected.items():
  366. collected[key] = val + order_term
  367. if func is not None:
  368. collected = {
  369. key: func(val) for key, val in collected.items()}
  370. if evaluate:
  371. return Add(*[key*val for key, val in collected.items()])
  372. else:
  373. return collected
  374. def rcollect(expr, *vars):
  375. """
  376. Recursively collect sums in an expression.
  377. Examples
  378. ========
  379. >>> from sympy.simplify import rcollect
  380. >>> from sympy.abc import x, y
  381. >>> expr = (x**2*y + x*y + x + y)/(x + y)
  382. >>> rcollect(expr, y)
  383. (x + y*(x**2 + x + 1))/(x + y)
  384. See Also
  385. ========
  386. collect, collect_const, collect_sqrt
  387. """
  388. if expr.is_Atom or not expr.has(*vars):
  389. return expr
  390. else:
  391. expr = expr.__class__(*[rcollect(arg, *vars) for arg in expr.args])
  392. if expr.is_Add:
  393. return collect(expr, vars)
  394. else:
  395. return expr
  396. def collect_sqrt(expr, evaluate=None):
  397. """Return expr with terms having common square roots collected together.
  398. If ``evaluate`` is False a count indicating the number of sqrt-containing
  399. terms will be returned and, if non-zero, the terms of the Add will be
  400. returned, else the expression itself will be returned as a single term.
  401. If ``evaluate`` is True, the expression with any collected terms will be
  402. returned.
  403. Note: since I = sqrt(-1), it is collected, too.
  404. Examples
  405. ========
  406. >>> from sympy import sqrt
  407. >>> from sympy.simplify.radsimp import collect_sqrt
  408. >>> from sympy.abc import a, b
  409. >>> r2, r3, r5 = [sqrt(i) for i in [2, 3, 5]]
  410. >>> collect_sqrt(a*r2 + b*r2)
  411. sqrt(2)*(a + b)
  412. >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r3)
  413. sqrt(2)*(a + b) + sqrt(3)*(a + b)
  414. >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5)
  415. sqrt(3)*a + sqrt(5)*b + sqrt(2)*(a + b)
  416. If evaluate is False then the arguments will be sorted and
  417. returned as a list and a count of the number of sqrt-containing
  418. terms will be returned:
  419. >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5, evaluate=False)
  420. ((sqrt(3)*a, sqrt(5)*b, sqrt(2)*(a + b)), 3)
  421. >>> collect_sqrt(a*sqrt(2) + b, evaluate=False)
  422. ((b, sqrt(2)*a), 1)
  423. >>> collect_sqrt(a + b, evaluate=False)
  424. ((a + b,), 0)
  425. See Also
  426. ========
  427. collect, collect_const, rcollect
  428. """
  429. if evaluate is None:
  430. evaluate = global_parameters.evaluate
  431. # this step will help to standardize any complex arguments
  432. # of sqrts
  433. coeff, expr = expr.as_content_primitive()
  434. vars = set()
  435. for a in Add.make_args(expr):
  436. for m in a.args_cnc()[0]:
  437. if m.is_number and (
  438. m.is_Pow and m.exp.is_Rational and m.exp.q == 2 or
  439. m is S.ImaginaryUnit):
  440. vars.add(m)
  441. # we only want radicals, so exclude Number handling; in this case
  442. # d will be evaluated
  443. d = collect_const(expr, *vars, Numbers=False)
  444. hit = expr != d
  445. if not evaluate:
  446. nrad = 0
  447. # make the evaluated args canonical
  448. args = list(ordered(Add.make_args(d)))
  449. for i, m in enumerate(args):
  450. c, nc = m.args_cnc()
  451. for ci in c:
  452. # XXX should this be restricted to ci.is_number as above?
  453. if ci.is_Pow and ci.exp.is_Rational and ci.exp.q == 2 or \
  454. ci is S.ImaginaryUnit:
  455. nrad += 1
  456. break
  457. args[i] *= coeff
  458. if not (hit or nrad):
  459. args = [Add(*args)]
  460. return tuple(args), nrad
  461. return coeff*d
  462. def collect_abs(expr):
  463. """Return ``expr`` with arguments of multiple Abs in a term collected
  464. under a single instance.
  465. Examples
  466. ========
  467. >>> from sympy.simplify.radsimp import collect_abs
  468. >>> from sympy.abc import x
  469. >>> collect_abs(abs(x + 1)/abs(x**2 - 1))
  470. Abs((x + 1)/(x**2 - 1))
  471. >>> collect_abs(abs(1/x))
  472. Abs(1/x)
  473. """
  474. def _abs(mul):
  475. c, nc = mul.args_cnc()
  476. a = []
  477. o = []
  478. for i in c:
  479. if isinstance(i, Abs):
  480. a.append(i.args[0])
  481. elif isinstance(i, Pow) and isinstance(i.base, Abs) and i.exp.is_real:
  482. a.append(i.base.args[0]**i.exp)
  483. else:
  484. o.append(i)
  485. if len(a) < 2 and not any(i.exp.is_negative for i in a if isinstance(i, Pow)):
  486. return mul
  487. absarg = Mul(*a)
  488. A = Abs(absarg)
  489. args = [A]
  490. args.extend(o)
  491. if not A.has(Abs):
  492. args.extend(nc)
  493. return Mul(*args)
  494. if not isinstance(A, Abs):
  495. # reevaluate and make it unevaluated
  496. A = Abs(absarg, evaluate=False)
  497. args[0] = A
  498. _mulsort(args)
  499. args.extend(nc) # nc always go last
  500. return Mul._from_args(args, is_commutative=not nc)
  501. return expr.replace(
  502. lambda x: isinstance(x, Mul),
  503. lambda x: _abs(x)).replace(
  504. lambda x: isinstance(x, Pow),
  505. lambda x: _abs(x))
  506. def collect_const(expr, *vars, Numbers=True):
  507. """A non-greedy collection of terms with similar number coefficients in
  508. an Add expr. If ``vars`` is given then only those constants will be
  509. targeted. Although any Number can also be targeted, if this is not
  510. desired set ``Numbers=False`` and no Float or Rational will be collected.
  511. Parameters
  512. ==========
  513. expr : SymPy expression
  514. This parameter defines the expression the expression from which
  515. terms with similar coefficients are to be collected. A non-Add
  516. expression is returned as it is.
  517. vars : variable length collection of Numbers, optional
  518. Specifies the constants to target for collection. Can be multiple in
  519. number.
  520. Numbers : bool
  521. Specifies to target all instance of
  522. :class:`sympy.core.numbers.Number` class. If ``Numbers=False``, then
  523. no Float or Rational will be collected.
  524. Returns
  525. =======
  526. expr : Expr
  527. Returns an expression with similar coefficient terms collected.
  528. Examples
  529. ========
  530. >>> from sympy import sqrt
  531. >>> from sympy.abc import s, x, y, z
  532. >>> from sympy.simplify.radsimp import collect_const
  533. >>> collect_const(sqrt(3) + sqrt(3)*(1 + sqrt(2)))
  534. sqrt(3)*(sqrt(2) + 2)
  535. >>> collect_const(sqrt(3)*s + sqrt(7)*s + sqrt(3) + sqrt(7))
  536. (sqrt(3) + sqrt(7))*(s + 1)
  537. >>> s = sqrt(2) + 2
  538. >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7))
  539. (sqrt(2) + 3)*(sqrt(3) + sqrt(7))
  540. >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7), sqrt(3))
  541. sqrt(7) + sqrt(3)*(sqrt(2) + 3) + sqrt(7)*(sqrt(2) + 2)
  542. The collection is sign-sensitive, giving higher precedence to the
  543. unsigned values:
  544. >>> collect_const(x - y - z)
  545. x - (y + z)
  546. >>> collect_const(-y - z)
  547. -(y + z)
  548. >>> collect_const(2*x - 2*y - 2*z, 2)
  549. 2*(x - y - z)
  550. >>> collect_const(2*x - 2*y - 2*z, -2)
  551. 2*x - 2*(y + z)
  552. See Also
  553. ========
  554. collect, collect_sqrt, rcollect
  555. """
  556. if not expr.is_Add:
  557. return expr
  558. recurse = False
  559. if not vars:
  560. recurse = True
  561. vars = set()
  562. for a in expr.args:
  563. for m in Mul.make_args(a):
  564. if m.is_number:
  565. vars.add(m)
  566. else:
  567. vars = sympify(vars)
  568. if not Numbers:
  569. vars = [v for v in vars if not v.is_Number]
  570. vars = list(ordered(vars))
  571. for v in vars:
  572. terms = defaultdict(list)
  573. Fv = Factors(v)
  574. for m in Add.make_args(expr):
  575. f = Factors(m)
  576. q, r = f.div(Fv)
  577. if r.is_one:
  578. # only accept this as a true factor if
  579. # it didn't change an exponent from an Integer
  580. # to a non-Integer, e.g. 2/sqrt(2) -> sqrt(2)
  581. # -- we aren't looking for this sort of change
  582. fwas = f.factors.copy()
  583. fnow = q.factors
  584. if not any(k in fwas and fwas[k].is_Integer and not
  585. fnow[k].is_Integer for k in fnow):
  586. terms[v].append(q.as_expr())
  587. continue
  588. terms[S.One].append(m)
  589. args = []
  590. hit = False
  591. uneval = False
  592. for k in ordered(terms):
  593. v = terms[k]
  594. if k is S.One:
  595. args.extend(v)
  596. continue
  597. if len(v) > 1:
  598. v = Add(*v)
  599. hit = True
  600. if recurse and v != expr:
  601. vars.append(v)
  602. else:
  603. v = v[0]
  604. # be careful not to let uneval become True unless
  605. # it must be because it's going to be more expensive
  606. # to rebuild the expression as an unevaluated one
  607. if Numbers and k.is_Number and v.is_Add:
  608. args.append(_keep_coeff(k, v, sign=True))
  609. uneval = True
  610. else:
  611. args.append(k*v)
  612. if hit:
  613. if uneval:
  614. expr = _unevaluated_Add(*args)
  615. else:
  616. expr = Add(*args)
  617. if not expr.is_Add:
  618. break
  619. return expr
  620. def radsimp(expr, symbolic=True, max_terms=4):
  621. r"""
  622. Rationalize the denominator by removing square roots.
  623. Explanation
  624. ===========
  625. The expression returned from radsimp must be used with caution
  626. since if the denominator contains symbols, it will be possible to make
  627. substitutions that violate the assumptions of the simplification process:
  628. that for a denominator matching a + b*sqrt(c), a != +/-b*sqrt(c). (If
  629. there are no symbols, this assumptions is made valid by collecting terms
  630. of sqrt(c) so the match variable ``a`` does not contain ``sqrt(c)``.) If
  631. you do not want the simplification to occur for symbolic denominators, set
  632. ``symbolic`` to False.
  633. If there are more than ``max_terms`` radical terms then the expression is
  634. returned unchanged.
  635. Examples
  636. ========
  637. >>> from sympy import radsimp, sqrt, Symbol, pprint
  638. >>> from sympy import factor_terms, fraction, signsimp
  639. >>> from sympy.simplify.radsimp import collect_sqrt
  640. >>> from sympy.abc import a, b, c
  641. >>> radsimp(1/(2 + sqrt(2)))
  642. (2 - sqrt(2))/2
  643. >>> x,y = map(Symbol, 'xy')
  644. >>> e = ((2 + 2*sqrt(2))*x + (2 + sqrt(8))*y)/(2 + sqrt(2))
  645. >>> radsimp(e)
  646. sqrt(2)*(x + y)
  647. No simplification beyond removal of the gcd is done. One might
  648. want to polish the result a little, however, by collecting
  649. square root terms:
  650. >>> r2 = sqrt(2)
  651. >>> r5 = sqrt(5)
  652. >>> ans = radsimp(1/(y*r2 + x*r2 + a*r5 + b*r5)); pprint(ans)
  653. ___ ___ ___ ___
  654. \/ 5 *a + \/ 5 *b - \/ 2 *x - \/ 2 *y
  655. ------------------------------------------
  656. 2 2 2 2
  657. 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y
  658. >>> n, d = fraction(ans)
  659. >>> pprint(factor_terms(signsimp(collect_sqrt(n))/d, radical=True))
  660. ___ ___
  661. \/ 5 *(a + b) - \/ 2 *(x + y)
  662. ------------------------------------------
  663. 2 2 2 2
  664. 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y
  665. If radicals in the denominator cannot be removed or there is no denominator,
  666. the original expression will be returned.
  667. >>> radsimp(sqrt(2)*x + sqrt(2))
  668. sqrt(2)*x + sqrt(2)
  669. Results with symbols will not always be valid for all substitutions:
  670. >>> eq = 1/(a + b*sqrt(c))
  671. >>> eq.subs(a, b*sqrt(c))
  672. 1/(2*b*sqrt(c))
  673. >>> radsimp(eq).subs(a, b*sqrt(c))
  674. nan
  675. If ``symbolic=False``, symbolic denominators will not be transformed (but
  676. numeric denominators will still be processed):
  677. >>> radsimp(eq, symbolic=False)
  678. 1/(a + b*sqrt(c))
  679. """
  680. from sympy.core.expr import Expr
  681. from sympy.simplify.simplify import signsimp
  682. syms = symbols("a:d A:D")
  683. def _num(rterms):
  684. # return the multiplier that will simplify the expression described
  685. # by rterms [(sqrt arg, coeff), ... ]
  686. a, b, c, d, A, B, C, D = syms
  687. if len(rterms) == 2:
  688. reps = dict(list(zip([A, a, B, b], [j for i in rterms for j in i])))
  689. return (
  690. sqrt(A)*a - sqrt(B)*b).xreplace(reps)
  691. if len(rterms) == 3:
  692. reps = dict(list(zip([A, a, B, b, C, c], [j for i in rterms for j in i])))
  693. return (
  694. (sqrt(A)*a + sqrt(B)*b - sqrt(C)*c)*(2*sqrt(A)*sqrt(B)*a*b - A*a**2 -
  695. B*b**2 + C*c**2)).xreplace(reps)
  696. elif len(rterms) == 4:
  697. reps = dict(list(zip([A, a, B, b, C, c, D, d], [j for i in rterms for j in i])))
  698. return ((sqrt(A)*a + sqrt(B)*b - sqrt(C)*c - sqrt(D)*d)*(2*sqrt(A)*sqrt(B)*a*b
  699. - A*a**2 - B*b**2 - 2*sqrt(C)*sqrt(D)*c*d + C*c**2 +
  700. D*d**2)*(-8*sqrt(A)*sqrt(B)*sqrt(C)*sqrt(D)*a*b*c*d + A**2*a**4 -
  701. 2*A*B*a**2*b**2 - 2*A*C*a**2*c**2 - 2*A*D*a**2*d**2 + B**2*b**4 -
  702. 2*B*C*b**2*c**2 - 2*B*D*b**2*d**2 + C**2*c**4 - 2*C*D*c**2*d**2 +
  703. D**2*d**4)).xreplace(reps)
  704. elif len(rterms) == 1:
  705. return sqrt(rterms[0][0])
  706. else:
  707. raise NotImplementedError
  708. def ispow2(d, log2=False):
  709. if not d.is_Pow:
  710. return False
  711. e = d.exp
  712. if e.is_Rational and e.q == 2 or symbolic and denom(e) == 2:
  713. return True
  714. if log2:
  715. q = 1
  716. if e.is_Rational:
  717. q = e.q
  718. elif symbolic:
  719. d = denom(e)
  720. if d.is_Integer:
  721. q = d
  722. if q != 1 and log(q, 2).is_Integer:
  723. return True
  724. return False
  725. def handle(expr):
  726. # Handle first reduces to the case
  727. # expr = 1/d, where d is an add, or d is base**p/2.
  728. # We do this by recursively calling handle on each piece.
  729. from sympy.simplify.simplify import nsimplify
  730. if expr.is_Atom:
  731. return expr
  732. elif not isinstance(expr, Expr):
  733. return expr.func(*[handle(a) for a in expr.args])
  734. n, d = fraction(expr)
  735. if d.is_Atom and n.is_Atom:
  736. return expr
  737. elif not n.is_Atom:
  738. n = n.func(*[handle(a) for a in n.args])
  739. return _unevaluated_Mul(n, handle(1/d))
  740. elif n is not S.One:
  741. return _unevaluated_Mul(n, handle(1/d))
  742. elif d.is_Mul:
  743. return _unevaluated_Mul(*[handle(1/d) for d in d.args])
  744. # By this step, expr is 1/d, and d is not a mul.
  745. if not symbolic and d.free_symbols:
  746. return expr
  747. if ispow2(d):
  748. d2 = sqrtdenest(sqrt(d.base))**numer(d.exp)
  749. if d2 != d:
  750. return handle(1/d2)
  751. elif d.is_Pow and (d.exp.is_integer or d.base.is_positive):
  752. # (1/d**i) = (1/d)**i
  753. return handle(1/d.base)**d.exp
  754. if not (d.is_Add or ispow2(d)):
  755. return 1/d.func(*[handle(a) for a in d.args])
  756. # handle 1/d treating d as an Add (though it may not be)
  757. keep = True # keep changes that are made
  758. # flatten it and collect radicals after checking for special
  759. # conditions
  760. d = _mexpand(d)
  761. # did it change?
  762. if d.is_Atom:
  763. return 1/d
  764. # is it a number that might be handled easily?
  765. if d.is_number:
  766. _d = nsimplify(d)
  767. if _d.is_Number and _d.equals(d):
  768. return 1/_d
  769. while True:
  770. # collect similar terms
  771. collected = defaultdict(list)
  772. for m in Add.make_args(d): # d might have become non-Add
  773. p2 = []
  774. other = []
  775. for i in Mul.make_args(m):
  776. if ispow2(i, log2=True):
  777. p2.append(i.base if i.exp is S.Half else i.base**(2*i.exp))
  778. elif i is S.ImaginaryUnit:
  779. p2.append(S.NegativeOne)
  780. else:
  781. other.append(i)
  782. collected[tuple(ordered(p2))].append(Mul(*other))
  783. rterms = list(ordered(list(collected.items())))
  784. rterms = [(Mul(*i), Add(*j)) for i, j in rterms]
  785. nrad = len(rterms) - (1 if rterms[0][0] is S.One else 0)
  786. if nrad < 1:
  787. break
  788. elif nrad > max_terms:
  789. # there may have been invalid operations leading to this point
  790. # so don't keep changes, e.g. this expression is troublesome
  791. # in collecting terms so as not to raise the issue of 2834:
  792. # r = sqrt(sqrt(5) + 5)
  793. # eq = 1/(sqrt(5)*r + 2*sqrt(5)*sqrt(-sqrt(5) + 5) + 5*r)
  794. keep = False
  795. break
  796. if len(rterms) > 4:
  797. # in general, only 4 terms can be removed with repeated squaring
  798. # but other considerations can guide selection of radical terms
  799. # so that radicals are removed
  800. if all(x.is_Integer and (y**2).is_Rational for x, y in rterms):
  801. nd, d = rad_rationalize(S.One, Add._from_args(
  802. [sqrt(x)*y for x, y in rterms]))
  803. n *= nd
  804. else:
  805. # is there anything else that might be attempted?
  806. keep = False
  807. break
  808. from sympy.simplify.powsimp import powsimp, powdenest
  809. num = powsimp(_num(rterms))
  810. n *= num
  811. d *= num
  812. d = powdenest(_mexpand(d), force=symbolic)
  813. if d.has(S.Zero, nan, zoo):
  814. return expr
  815. if d.is_Atom:
  816. break
  817. if not keep:
  818. return expr
  819. return _unevaluated_Mul(n, 1/d)
  820. if not isinstance(expr, Expr):
  821. return expr.func(*[radsimp(a, symbolic=symbolic, max_terms=max_terms) for a in expr.args])
  822. coeff, expr = expr.as_coeff_Add()
  823. expr = expr.normal()
  824. old = fraction(expr)
  825. n, d = fraction(handle(expr))
  826. if old != (n, d):
  827. if not d.is_Atom:
  828. was = (n, d)
  829. n = signsimp(n, evaluate=False)
  830. d = signsimp(d, evaluate=False)
  831. u = Factors(_unevaluated_Mul(n, 1/d))
  832. u = _unevaluated_Mul(*[k**v for k, v in u.factors.items()])
  833. n, d = fraction(u)
  834. if old == (n, d):
  835. n, d = was
  836. n = expand_mul(n)
  837. if d.is_Number or d.is_Add:
  838. n2, d2 = fraction(gcd_terms(_unevaluated_Mul(n, 1/d)))
  839. if d2.is_Number or (d2.count_ops() <= d.count_ops()):
  840. n, d = [signsimp(i) for i in (n2, d2)]
  841. if n.is_Mul and n.args[0].is_Number:
  842. n = n.func(*n.args)
  843. return coeff + _unevaluated_Mul(n, 1/d)
  844. def rad_rationalize(num, den):
  845. """
  846. Rationalize ``num/den`` by removing square roots in the denominator;
  847. num and den are sum of terms whose squares are positive rationals.
  848. Examples
  849. ========
  850. >>> from sympy import sqrt
  851. >>> from sympy.simplify.radsimp import rad_rationalize
  852. >>> rad_rationalize(sqrt(3), 1 + sqrt(2)/3)
  853. (-sqrt(3) + sqrt(6)/3, -7/9)
  854. """
  855. if not den.is_Add:
  856. return num, den
  857. g, a, b = split_surds(den)
  858. a = a*sqrt(g)
  859. num = _mexpand((a - b)*num)
  860. den = _mexpand(a**2 - b**2)
  861. return rad_rationalize(num, den)
  862. def fraction(expr, exact=False):
  863. """Returns a pair with expression's numerator and denominator.
  864. If the given expression is not a fraction then this function
  865. will return the tuple (expr, 1).
  866. This function will not make any attempt to simplify nested
  867. fractions or to do any term rewriting at all.
  868. If only one of the numerator/denominator pair is needed then
  869. use numer(expr) or denom(expr) functions respectively.
  870. >>> from sympy import fraction, Rational, Symbol
  871. >>> from sympy.abc import x, y
  872. >>> fraction(x/y)
  873. (x, y)
  874. >>> fraction(x)
  875. (x, 1)
  876. >>> fraction(1/y**2)
  877. (1, y**2)
  878. >>> fraction(x*y/2)
  879. (x*y, 2)
  880. >>> fraction(Rational(1, 2))
  881. (1, 2)
  882. This function will also work fine with assumptions:
  883. >>> k = Symbol('k', negative=True)
  884. >>> fraction(x * y**k)
  885. (x, y**(-k))
  886. If we know nothing about sign of some exponent and ``exact``
  887. flag is unset, then the exponent's structure will
  888. be analyzed and pretty fraction will be returned:
  889. >>> from sympy import exp, Mul
  890. >>> fraction(2*x**(-y))
  891. (2, x**y)
  892. >>> fraction(exp(-x))
  893. (1, exp(x))
  894. >>> fraction(exp(-x), exact=True)
  895. (exp(-x), 1)
  896. The ``exact`` flag will also keep any unevaluated Muls from
  897. being evaluated:
  898. >>> u = Mul(2, x + 1, evaluate=False)
  899. >>> fraction(u)
  900. (2*x + 2, 1)
  901. >>> fraction(u, exact=True)
  902. (2*(x + 1), 1)
  903. """
  904. expr = sympify(expr)
  905. numer, denom = [], []
  906. for term in Mul.make_args(expr):
  907. if term.is_commutative and (term.is_Pow or isinstance(term, exp)):
  908. b, ex = term.as_base_exp()
  909. if ex.is_negative:
  910. if ex is S.NegativeOne:
  911. denom.append(b)
  912. elif exact:
  913. if ex.is_constant():
  914. denom.append(Pow(b, -ex))
  915. else:
  916. numer.append(term)
  917. else:
  918. denom.append(Pow(b, -ex))
  919. elif ex.is_positive:
  920. numer.append(term)
  921. elif not exact and ex.is_Mul:
  922. n, d = term.as_numer_denom() # this will cause evaluation
  923. if n != 1:
  924. numer.append(n)
  925. denom.append(d)
  926. else:
  927. numer.append(term)
  928. elif term.is_Rational and not term.is_Integer:
  929. if term.p != 1:
  930. numer.append(term.p)
  931. denom.append(term.q)
  932. else:
  933. numer.append(term)
  934. return Mul(*numer, evaluate=not exact), Mul(*denom, evaluate=not exact)
  935. def numer(expr, exact=False): # default matches fraction's default
  936. return fraction(expr, exact=exact)[0]
  937. def denom(expr, exact=False): # default matches fraction's default
  938. return fraction(expr, exact=exact)[1]
  939. def fraction_expand(expr, **hints):
  940. return expr.expand(frac=True, **hints)
  941. def numer_expand(expr, **hints):
  942. # default matches fraction's default
  943. a, b = fraction(expr, exact=hints.get('exact', False))
  944. return a.expand(numer=True, **hints) / b
  945. def denom_expand(expr, **hints):
  946. # default matches fraction's default
  947. a, b = fraction(expr, exact=hints.get('exact', False))
  948. return a / b.expand(denom=True, **hints)
  949. expand_numer = numer_expand
  950. expand_denom = denom_expand
  951. expand_fraction = fraction_expand
  952. def split_surds(expr):
  953. """
  954. Split an expression with terms whose squares are positive rationals
  955. into a sum of terms whose surds squared have gcd equal to g
  956. and a sum of terms with surds squared prime with g.
  957. Examples
  958. ========
  959. >>> from sympy import sqrt
  960. >>> from sympy.simplify.radsimp import split_surds
  961. >>> split_surds(3*sqrt(3) + sqrt(5)/7 + sqrt(6) + sqrt(10) + sqrt(15))
  962. (3, sqrt(2) + sqrt(5) + 3, sqrt(5)/7 + sqrt(10))
  963. """
  964. args = sorted(expr.args, key=default_sort_key)
  965. coeff_muls = [x.as_coeff_Mul() for x in args]
  966. surds = [x[1]**2 for x in coeff_muls if x[1].is_Pow]
  967. surds.sort(key=default_sort_key)
  968. g, b1, b2 = _split_gcd(*surds)
  969. g2 = g
  970. if not b2 and len(b1) >= 2:
  971. b1n = [x/g for x in b1]
  972. b1n = [x for x in b1n if x != 1]
  973. # only a common factor has been factored; split again
  974. g1, b1n, b2 = _split_gcd(*b1n)
  975. g2 = g*g1
  976. a1v, a2v = [], []
  977. for c, s in coeff_muls:
  978. if s.is_Pow and s.exp == S.Half:
  979. s1 = s.base
  980. if s1 in b1:
  981. a1v.append(c*sqrt(s1/g2))
  982. else:
  983. a2v.append(c*s)
  984. else:
  985. a2v.append(c*s)
  986. a = Add(*a1v)
  987. b = Add(*a2v)
  988. return g2, a, b
  989. def _split_gcd(*a):
  990. """
  991. Split the list of integers ``a`` into a list of integers, ``a1`` having
  992. ``g = gcd(a1)``, and a list ``a2`` whose elements are not divisible by
  993. ``g``. Returns ``g, a1, a2``.
  994. Examples
  995. ========
  996. >>> from sympy.simplify.radsimp import _split_gcd
  997. >>> _split_gcd(55, 35, 22, 14, 77, 10)
  998. (5, [55, 35, 10], [22, 14, 77])
  999. """
  1000. g = a[0]
  1001. b1 = [g]
  1002. b2 = []
  1003. for x in a[1:]:
  1004. g1 = gcd(g, x)
  1005. if g1 == 1:
  1006. b2.append(x)
  1007. else:
  1008. g = g1
  1009. b1.append(x)
  1010. return g, b1, b2