radsimp.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  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. while order > 0:
  171. term, order = Derivative(term, var), order - 1
  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. for s in expr.variables:
  193. if s != s0:
  194. raise NotImplementedError(
  195. 'Improve MV Derivative support in collect')
  196. if s0 == sym:
  197. expr, order = expr.expr, order + len(expr.variables)
  198. else:
  199. break
  200. return expr, (sym, Rational(order))
  201. def parse_term(expr):
  202. """Parses expression expr and outputs tuple (sexpr, rat_expo,
  203. sym_expo, deriv)
  204. where:
  205. - sexpr is the base expression
  206. - rat_expo is the rational exponent that sexpr is raised to
  207. - sym_expo is the symbolic exponent that sexpr is raised to
  208. - deriv contains the derivatives of the expression
  209. For example, the output of x would be (x, 1, None, None)
  210. the output of 2**x would be (2, 1, x, None).
  211. """
  212. rat_expo, sym_expo = S.One, None
  213. sexpr, deriv = expr, None
  214. if expr.is_Pow:
  215. if isinstance(expr.base, Derivative):
  216. sexpr, deriv = parse_derivative(expr.base)
  217. else:
  218. sexpr = expr.base
  219. if expr.base == S.Exp1:
  220. arg = expr.exp
  221. if arg.is_Rational:
  222. sexpr, rat_expo = S.Exp1, arg
  223. elif arg.is_Mul:
  224. coeff, tail = arg.as_coeff_Mul(rational=True)
  225. sexpr, rat_expo = exp(tail), coeff
  226. elif expr.exp.is_Number:
  227. rat_expo = expr.exp
  228. else:
  229. coeff, tail = expr.exp.as_coeff_Mul()
  230. if coeff.is_Number:
  231. rat_expo, sym_expo = coeff, tail
  232. else:
  233. sym_expo = expr.exp
  234. elif isinstance(expr, exp):
  235. arg = expr.exp
  236. if arg.is_Rational:
  237. sexpr, rat_expo = S.Exp1, arg
  238. elif arg.is_Mul:
  239. coeff, tail = arg.as_coeff_Mul(rational=True)
  240. sexpr, rat_expo = exp(tail), coeff
  241. elif isinstance(expr, Derivative):
  242. sexpr, deriv = parse_derivative(expr)
  243. return sexpr, rat_expo, sym_expo, deriv
  244. def parse_expression(terms, pattern):
  245. """Parse terms searching for a pattern.
  246. Terms is a list of tuples as returned by parse_terms;
  247. Pattern is an expression treated as a product of factors.
  248. """
  249. pattern = Mul.make_args(pattern)
  250. if len(terms) < len(pattern):
  251. # pattern is longer than matched product
  252. # so no chance for positive parsing result
  253. return None
  254. else:
  255. pattern = [parse_term(elem) for elem in pattern]
  256. terms = terms[:] # need a copy
  257. elems, common_expo, has_deriv = [], None, False
  258. for elem, e_rat, e_sym, e_ord in pattern:
  259. if elem.is_Number and e_rat == 1 and e_sym is None:
  260. # a constant is a match for everything
  261. continue
  262. for j in range(len(terms)):
  263. if terms[j] is None:
  264. continue
  265. term, t_rat, t_sym, t_ord = terms[j]
  266. # keeping track of whether one of the terms had
  267. # a derivative or not as this will require rebuilding
  268. # the expression later
  269. if t_ord is not None:
  270. has_deriv = True
  271. if (term.match(elem) is not None and
  272. (t_sym == e_sym or t_sym is not None and
  273. e_sym is not None and
  274. t_sym.match(e_sym) is not None)):
  275. if exact is False:
  276. # we don't have to be exact so find common exponent
  277. # for both expression's term and pattern's element
  278. expo = t_rat / e_rat
  279. if common_expo is None:
  280. # first time
  281. common_expo = expo
  282. else:
  283. # common exponent was negotiated before so
  284. # there is no chance for a pattern match unless
  285. # common and current exponents are equal
  286. if common_expo != expo:
  287. common_expo = 1
  288. else:
  289. # we ought to be exact so all fields of
  290. # interest must match in every details
  291. if e_rat != t_rat or e_ord != t_ord:
  292. continue
  293. # found common term so remove it from the expression
  294. # and try to match next element in the pattern
  295. elems.append(terms[j])
  296. terms[j] = None
  297. break
  298. else:
  299. # pattern element not found
  300. return None
  301. return [_f for _f in terms if _f], elems, common_expo, has_deriv
  302. if evaluate:
  303. if expr.is_Add:
  304. o = expr.getO() or 0
  305. expr = expr.func(*[
  306. collect(a, syms, func, True, exact, distribute_order_term)
  307. for a in expr.args if a != o]) + o
  308. elif expr.is_Mul:
  309. return expr.func(*[
  310. collect(term, syms, func, True, exact, distribute_order_term)
  311. for term in expr.args])
  312. elif expr.is_Pow:
  313. b = collect(
  314. expr.base, syms, func, True, exact, distribute_order_term)
  315. return Pow(b, expr.exp)
  316. syms = [expand_power_base(i, deep=False) for i in syms]
  317. order_term = None
  318. if distribute_order_term:
  319. order_term = expr.getO()
  320. if order_term is not None:
  321. if order_term.has(*syms):
  322. order_term = None
  323. else:
  324. expr = expr.removeO()
  325. summa = [expand_power_base(i, deep=False) for i in Add.make_args(expr)]
  326. collected, disliked = defaultdict(list), S.Zero
  327. for product in summa:
  328. c, nc = product.args_cnc(split_1=False)
  329. args = list(ordered(c)) + nc
  330. terms = [parse_term(i) for i in args]
  331. small_first = True
  332. for symbol in syms:
  333. if isinstance(symbol, Derivative) and small_first:
  334. terms = list(reversed(terms))
  335. small_first = not small_first
  336. result = parse_expression(terms, symbol)
  337. if result is not None:
  338. if not symbol.is_commutative:
  339. raise AttributeError("Can not collect noncommutative symbol")
  340. terms, elems, common_expo, has_deriv = result
  341. # when there was derivative in current pattern we
  342. # will need to rebuild its expression from scratch
  343. if not has_deriv:
  344. margs = []
  345. for elem in elems:
  346. if elem[2] is None:
  347. e = elem[1]
  348. else:
  349. e = elem[1]*elem[2]
  350. margs.append(Pow(elem[0], e))
  351. index = Mul(*margs)
  352. else:
  353. index = make_expression(elems)
  354. terms = expand_power_base(make_expression(terms), deep=False)
  355. index = expand_power_base(index, deep=False)
  356. collected[index].append(terms)
  357. break
  358. else:
  359. # none of the patterns matched
  360. disliked += product
  361. # add terms now for each key
  362. collected = {k: Add(*v) for k, v in collected.items()}
  363. if disliked is not S.Zero:
  364. collected[S.One] = disliked
  365. if order_term is not None:
  366. for key, val in collected.items():
  367. collected[key] = val + order_term
  368. if func is not None:
  369. collected = {
  370. key: func(val) for key, val in collected.items()}
  371. if evaluate:
  372. return Add(*[key*val for key, val in collected.items()])
  373. else:
  374. return collected
  375. def rcollect(expr, *vars):
  376. """
  377. Recursively collect sums in an expression.
  378. Examples
  379. ========
  380. >>> from sympy.simplify import rcollect
  381. >>> from sympy.abc import x, y
  382. >>> expr = (x**2*y + x*y + x + y)/(x + y)
  383. >>> rcollect(expr, y)
  384. (x + y*(x**2 + x + 1))/(x + y)
  385. See Also
  386. ========
  387. collect, collect_const, collect_sqrt
  388. """
  389. if expr.is_Atom or not expr.has(*vars):
  390. return expr
  391. else:
  392. expr = expr.__class__(*[rcollect(arg, *vars) for arg in expr.args])
  393. if expr.is_Add:
  394. return collect(expr, vars)
  395. else:
  396. return expr
  397. def collect_sqrt(expr, evaluate=None):
  398. """Return expr with terms having common square roots collected together.
  399. If ``evaluate`` is False a count indicating the number of sqrt-containing
  400. terms will be returned and, if non-zero, the terms of the Add will be
  401. returned, else the expression itself will be returned as a single term.
  402. If ``evaluate`` is True, the expression with any collected terms will be
  403. returned.
  404. Note: since I = sqrt(-1), it is collected, too.
  405. Examples
  406. ========
  407. >>> from sympy import sqrt
  408. >>> from sympy.simplify.radsimp import collect_sqrt
  409. >>> from sympy.abc import a, b
  410. >>> r2, r3, r5 = [sqrt(i) for i in [2, 3, 5]]
  411. >>> collect_sqrt(a*r2 + b*r2)
  412. sqrt(2)*(a + b)
  413. >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r3)
  414. sqrt(2)*(a + b) + sqrt(3)*(a + b)
  415. >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5)
  416. sqrt(3)*a + sqrt(5)*b + sqrt(2)*(a + b)
  417. If evaluate is False then the arguments will be sorted and
  418. returned as a list and a count of the number of sqrt-containing
  419. terms will be returned:
  420. >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5, evaluate=False)
  421. ((sqrt(3)*a, sqrt(5)*b, sqrt(2)*(a + b)), 3)
  422. >>> collect_sqrt(a*sqrt(2) + b, evaluate=False)
  423. ((b, sqrt(2)*a), 1)
  424. >>> collect_sqrt(a + b, evaluate=False)
  425. ((a + b,), 0)
  426. See Also
  427. ========
  428. collect, collect_const, rcollect
  429. """
  430. if evaluate is None:
  431. evaluate = global_parameters.evaluate
  432. # this step will help to standardize any complex arguments
  433. # of sqrts
  434. coeff, expr = expr.as_content_primitive()
  435. vars = set()
  436. for a in Add.make_args(expr):
  437. for m in a.args_cnc()[0]:
  438. if m.is_number and (
  439. m.is_Pow and m.exp.is_Rational and m.exp.q == 2 or
  440. m is S.ImaginaryUnit):
  441. vars.add(m)
  442. # we only want radicals, so exclude Number handling; in this case
  443. # d will be evaluated
  444. d = collect_const(expr, *vars, Numbers=False)
  445. hit = expr != d
  446. if not evaluate:
  447. nrad = 0
  448. # make the evaluated args canonical
  449. args = list(ordered(Add.make_args(d)))
  450. for i, m in enumerate(args):
  451. c, nc = m.args_cnc()
  452. for ci in c:
  453. # XXX should this be restricted to ci.is_number as above?
  454. if ci.is_Pow and ci.exp.is_Rational and ci.exp.q == 2 or \
  455. ci is S.ImaginaryUnit:
  456. nrad += 1
  457. break
  458. args[i] *= coeff
  459. if not (hit or nrad):
  460. args = [Add(*args)]
  461. return tuple(args), nrad
  462. return coeff*d
  463. def collect_abs(expr):
  464. """Return ``expr`` with arguments of multiple Abs in a term collected
  465. under a single instance.
  466. Examples
  467. ========
  468. >>> from sympy.simplify.radsimp import collect_abs
  469. >>> from sympy.abc import x
  470. >>> collect_abs(abs(x + 1)/abs(x**2 - 1))
  471. Abs((x + 1)/(x**2 - 1))
  472. >>> collect_abs(abs(1/x))
  473. Abs(1/x)
  474. """
  475. def _abs(mul):
  476. c, nc = mul.args_cnc()
  477. a = []
  478. o = []
  479. for i in c:
  480. if isinstance(i, Abs):
  481. a.append(i.args[0])
  482. elif isinstance(i, Pow) and isinstance(i.base, Abs) and i.exp.is_real:
  483. a.append(i.base.args[0]**i.exp)
  484. else:
  485. o.append(i)
  486. if len(a) < 2 and not any(i.exp.is_negative for i in a if isinstance(i, Pow)):
  487. return mul
  488. absarg = Mul(*a)
  489. A = Abs(absarg)
  490. args = [A]
  491. args.extend(o)
  492. if not A.has(Abs):
  493. args.extend(nc)
  494. return Mul(*args)
  495. if not isinstance(A, Abs):
  496. # reevaluate and make it unevaluated
  497. A = Abs(absarg, evaluate=False)
  498. args[0] = A
  499. _mulsort(args)
  500. args.extend(nc) # nc always go last
  501. return Mul._from_args(args, is_commutative=not nc)
  502. return expr.replace(
  503. lambda x: isinstance(x, Mul),
  504. lambda x: _abs(x)).replace(
  505. lambda x: isinstance(x, Pow),
  506. lambda x: _abs(x))
  507. def collect_const(expr, *vars, Numbers=True):
  508. """A non-greedy collection of terms with similar number coefficients in
  509. an Add expr. If ``vars`` is given then only those constants will be
  510. targeted. Although any Number can also be targeted, if this is not
  511. desired set ``Numbers=False`` and no Float or Rational will be collected.
  512. Parameters
  513. ==========
  514. expr : SymPy expression
  515. This parameter defines the expression the expression from which
  516. terms with similar coefficients are to be collected. A non-Add
  517. expression is returned as it is.
  518. vars : variable length collection of Numbers, optional
  519. Specifies the constants to target for collection. Can be multiple in
  520. number.
  521. Numbers : bool
  522. Specifies to target all instance of
  523. :class:`sympy.core.numbers.Number` class. If ``Numbers=False``, then
  524. no Float or Rational will be collected.
  525. Returns
  526. =======
  527. expr : Expr
  528. Returns an expression with similar coefficient terms collected.
  529. Examples
  530. ========
  531. >>> from sympy import sqrt
  532. >>> from sympy.abc import s, x, y, z
  533. >>> from sympy.simplify.radsimp import collect_const
  534. >>> collect_const(sqrt(3) + sqrt(3)*(1 + sqrt(2)))
  535. sqrt(3)*(sqrt(2) + 2)
  536. >>> collect_const(sqrt(3)*s + sqrt(7)*s + sqrt(3) + sqrt(7))
  537. (sqrt(3) + sqrt(7))*(s + 1)
  538. >>> s = sqrt(2) + 2
  539. >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7))
  540. (sqrt(2) + 3)*(sqrt(3) + sqrt(7))
  541. >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7), sqrt(3))
  542. sqrt(7) + sqrt(3)*(sqrt(2) + 3) + sqrt(7)*(sqrt(2) + 2)
  543. The collection is sign-sensitive, giving higher precedence to the
  544. unsigned values:
  545. >>> collect_const(x - y - z)
  546. x - (y + z)
  547. >>> collect_const(-y - z)
  548. -(y + z)
  549. >>> collect_const(2*x - 2*y - 2*z, 2)
  550. 2*(x - y - z)
  551. >>> collect_const(2*x - 2*y - 2*z, -2)
  552. 2*x - 2*(y + z)
  553. See Also
  554. ========
  555. collect, collect_sqrt, rcollect
  556. """
  557. if not expr.is_Add:
  558. return expr
  559. recurse = False
  560. if not vars:
  561. recurse = True
  562. vars = set()
  563. for a in expr.args:
  564. for m in Mul.make_args(a):
  565. if m.is_number:
  566. vars.add(m)
  567. else:
  568. vars = sympify(vars)
  569. if not Numbers:
  570. vars = [v for v in vars if not v.is_Number]
  571. vars = list(ordered(vars))
  572. for v in vars:
  573. terms = defaultdict(list)
  574. Fv = Factors(v)
  575. for m in Add.make_args(expr):
  576. f = Factors(m)
  577. q, r = f.div(Fv)
  578. if r.is_one:
  579. # only accept this as a true factor if
  580. # it didn't change an exponent from an Integer
  581. # to a non-Integer, e.g. 2/sqrt(2) -> sqrt(2)
  582. # -- we aren't looking for this sort of change
  583. fwas = f.factors.copy()
  584. fnow = q.factors
  585. if not any(k in fwas and fwas[k].is_Integer and not
  586. fnow[k].is_Integer for k in fnow):
  587. terms[v].append(q.as_expr())
  588. continue
  589. terms[S.One].append(m)
  590. args = []
  591. hit = False
  592. uneval = False
  593. for k in ordered(terms):
  594. v = terms[k]
  595. if k is S.One:
  596. args.extend(v)
  597. continue
  598. if len(v) > 1:
  599. v = Add(*v)
  600. hit = True
  601. if recurse and v != expr:
  602. vars.append(v)
  603. else:
  604. v = v[0]
  605. # be careful not to let uneval become True unless
  606. # it must be because it's going to be more expensive
  607. # to rebuild the expression as an unevaluated one
  608. if Numbers and k.is_Number and v.is_Add:
  609. args.append(_keep_coeff(k, v, sign=True))
  610. uneval = True
  611. else:
  612. args.append(k*v)
  613. if hit:
  614. if uneval:
  615. expr = _unevaluated_Add(*args)
  616. else:
  617. expr = Add(*args)
  618. if not expr.is_Add:
  619. break
  620. return expr
  621. def radsimp(expr, symbolic=True, max_terms=4):
  622. r"""
  623. Rationalize the denominator by removing square roots.
  624. Explanation
  625. ===========
  626. The expression returned from radsimp must be used with caution
  627. since if the denominator contains symbols, it will be possible to make
  628. substitutions that violate the assumptions of the simplification process:
  629. that for a denominator matching a + b*sqrt(c), a != +/-b*sqrt(c). (If
  630. there are no symbols, this assumptions is made valid by collecting terms
  631. of sqrt(c) so the match variable ``a`` does not contain ``sqrt(c)``.) If
  632. you do not want the simplification to occur for symbolic denominators, set
  633. ``symbolic`` to False.
  634. If there are more than ``max_terms`` radical terms then the expression is
  635. returned unchanged.
  636. Examples
  637. ========
  638. >>> from sympy import radsimp, sqrt, Symbol, pprint
  639. >>> from sympy import factor_terms, fraction, signsimp
  640. >>> from sympy.simplify.radsimp import collect_sqrt
  641. >>> from sympy.abc import a, b, c
  642. >>> radsimp(1/(2 + sqrt(2)))
  643. (2 - sqrt(2))/2
  644. >>> x,y = map(Symbol, 'xy')
  645. >>> e = ((2 + 2*sqrt(2))*x + (2 + sqrt(8))*y)/(2 + sqrt(2))
  646. >>> radsimp(e)
  647. sqrt(2)*(x + y)
  648. No simplification beyond removal of the gcd is done. One might
  649. want to polish the result a little, however, by collecting
  650. square root terms:
  651. >>> r2 = sqrt(2)
  652. >>> r5 = sqrt(5)
  653. >>> ans = radsimp(1/(y*r2 + x*r2 + a*r5 + b*r5)); pprint(ans)
  654. ___ ___ ___ ___
  655. \/ 5 *a + \/ 5 *b - \/ 2 *x - \/ 2 *y
  656. ------------------------------------------
  657. 2 2 2 2
  658. 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y
  659. >>> n, d = fraction(ans)
  660. >>> pprint(factor_terms(signsimp(collect_sqrt(n))/d, radical=True))
  661. ___ ___
  662. \/ 5 *(a + b) - \/ 2 *(x + y)
  663. ------------------------------------------
  664. 2 2 2 2
  665. 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y
  666. If radicals in the denominator cannot be removed or there is no denominator,
  667. the original expression will be returned.
  668. >>> radsimp(sqrt(2)*x + sqrt(2))
  669. sqrt(2)*x + sqrt(2)
  670. Results with symbols will not always be valid for all substitutions:
  671. >>> eq = 1/(a + b*sqrt(c))
  672. >>> eq.subs(a, b*sqrt(c))
  673. 1/(2*b*sqrt(c))
  674. >>> radsimp(eq).subs(a, b*sqrt(c))
  675. nan
  676. If ``symbolic=False``, symbolic denominators will not be transformed (but
  677. numeric denominators will still be processed):
  678. >>> radsimp(eq, symbolic=False)
  679. 1/(a + b*sqrt(c))
  680. """
  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. n, d = fraction(expr)
  731. if expr.is_Atom or (d.is_Atom and n.is_Atom):
  732. return expr
  733. elif not n.is_Atom:
  734. n = n.func(*[handle(a) for a in n.args])
  735. return _unevaluated_Mul(n, handle(1/d))
  736. elif n is not S.One:
  737. return _unevaluated_Mul(n, handle(1/d))
  738. elif d.is_Mul:
  739. return _unevaluated_Mul(*[handle(1/d) for d in d.args])
  740. # By this step, expr is 1/d, and d is not a mul.
  741. if not symbolic and d.free_symbols:
  742. return expr
  743. if ispow2(d):
  744. d2 = sqrtdenest(sqrt(d.base))**numer(d.exp)
  745. if d2 != d:
  746. return handle(1/d2)
  747. elif d.is_Pow and (d.exp.is_integer or d.base.is_positive):
  748. # (1/d**i) = (1/d)**i
  749. return handle(1/d.base)**d.exp
  750. if not (d.is_Add or ispow2(d)):
  751. return 1/d.func(*[handle(a) for a in d.args])
  752. # handle 1/d treating d as an Add (though it may not be)
  753. keep = True # keep changes that are made
  754. # flatten it and collect radicals after checking for special
  755. # conditions
  756. d = _mexpand(d)
  757. # did it change?
  758. if d.is_Atom:
  759. return 1/d
  760. # is it a number that might be handled easily?
  761. if d.is_number:
  762. _d = nsimplify(d)
  763. if _d.is_Number and _d.equals(d):
  764. return 1/_d
  765. while True:
  766. # collect similar terms
  767. collected = defaultdict(list)
  768. for m in Add.make_args(d): # d might have become non-Add
  769. p2 = []
  770. other = []
  771. for i in Mul.make_args(m):
  772. if ispow2(i, log2=True):
  773. p2.append(i.base if i.exp is S.Half else i.base**(2*i.exp))
  774. elif i is S.ImaginaryUnit:
  775. p2.append(S.NegativeOne)
  776. else:
  777. other.append(i)
  778. collected[tuple(ordered(p2))].append(Mul(*other))
  779. rterms = list(ordered(list(collected.items())))
  780. rterms = [(Mul(*i), Add(*j)) for i, j in rterms]
  781. nrad = len(rterms) - (1 if rterms[0][0] is S.One else 0)
  782. if nrad < 1:
  783. break
  784. elif nrad > max_terms:
  785. # there may have been invalid operations leading to this point
  786. # so don't keep changes, e.g. this expression is troublesome
  787. # in collecting terms so as not to raise the issue of 2834:
  788. # r = sqrt(sqrt(5) + 5)
  789. # eq = 1/(sqrt(5)*r + 2*sqrt(5)*sqrt(-sqrt(5) + 5) + 5*r)
  790. keep = False
  791. break
  792. if len(rterms) > 4:
  793. # in general, only 4 terms can be removed with repeated squaring
  794. # but other considerations can guide selection of radical terms
  795. # so that radicals are removed
  796. if all(x.is_Integer and (y**2).is_Rational for x, y in rterms):
  797. nd, d = rad_rationalize(S.One, Add._from_args(
  798. [sqrt(x)*y for x, y in rterms]))
  799. n *= nd
  800. else:
  801. # is there anything else that might be attempted?
  802. keep = False
  803. break
  804. from sympy.simplify.powsimp import powsimp, powdenest
  805. num = powsimp(_num(rterms))
  806. n *= num
  807. d *= num
  808. d = powdenest(_mexpand(d), force=symbolic)
  809. if d.has(S.Zero, nan, zoo):
  810. return expr
  811. if d.is_Atom:
  812. break
  813. if not keep:
  814. return expr
  815. return _unevaluated_Mul(n, 1/d)
  816. coeff, expr = expr.as_coeff_Add()
  817. expr = expr.normal()
  818. old = fraction(expr)
  819. n, d = fraction(handle(expr))
  820. if old != (n, d):
  821. if not d.is_Atom:
  822. was = (n, d)
  823. n = signsimp(n, evaluate=False)
  824. d = signsimp(d, evaluate=False)
  825. u = Factors(_unevaluated_Mul(n, 1/d))
  826. u = _unevaluated_Mul(*[k**v for k, v in u.factors.items()])
  827. n, d = fraction(u)
  828. if old == (n, d):
  829. n, d = was
  830. n = expand_mul(n)
  831. if d.is_Number or d.is_Add:
  832. n2, d2 = fraction(gcd_terms(_unevaluated_Mul(n, 1/d)))
  833. if d2.is_Number or (d2.count_ops() <= d.count_ops()):
  834. n, d = [signsimp(i) for i in (n2, d2)]
  835. if n.is_Mul and n.args[0].is_Number:
  836. n = n.func(*n.args)
  837. return coeff + _unevaluated_Mul(n, 1/d)
  838. def rad_rationalize(num, den):
  839. """
  840. Rationalize ``num/den`` by removing square roots in the denominator;
  841. num and den are sum of terms whose squares are positive rationals.
  842. Examples
  843. ========
  844. >>> from sympy import sqrt
  845. >>> from sympy.simplify.radsimp import rad_rationalize
  846. >>> rad_rationalize(sqrt(3), 1 + sqrt(2)/3)
  847. (-sqrt(3) + sqrt(6)/3, -7/9)
  848. """
  849. if not den.is_Add:
  850. return num, den
  851. g, a, b = split_surds(den)
  852. a = a*sqrt(g)
  853. num = _mexpand((a - b)*num)
  854. den = _mexpand(a**2 - b**2)
  855. return rad_rationalize(num, den)
  856. def fraction(expr, exact=False):
  857. """Returns a pair with expression's numerator and denominator.
  858. If the given expression is not a fraction then this function
  859. will return the tuple (expr, 1).
  860. This function will not make any attempt to simplify nested
  861. fractions or to do any term rewriting at all.
  862. If only one of the numerator/denominator pair is needed then
  863. use numer(expr) or denom(expr) functions respectively.
  864. >>> from sympy import fraction, Rational, Symbol
  865. >>> from sympy.abc import x, y
  866. >>> fraction(x/y)
  867. (x, y)
  868. >>> fraction(x)
  869. (x, 1)
  870. >>> fraction(1/y**2)
  871. (1, y**2)
  872. >>> fraction(x*y/2)
  873. (x*y, 2)
  874. >>> fraction(Rational(1, 2))
  875. (1, 2)
  876. This function will also work fine with assumptions:
  877. >>> k = Symbol('k', negative=True)
  878. >>> fraction(x * y**k)
  879. (x, y**(-k))
  880. If we know nothing about sign of some exponent and ``exact``
  881. flag is unset, then structure this exponent's structure will
  882. be analyzed and pretty fraction will be returned:
  883. >>> from sympy import exp, Mul
  884. >>> fraction(2*x**(-y))
  885. (2, x**y)
  886. >>> fraction(exp(-x))
  887. (1, exp(x))
  888. >>> fraction(exp(-x), exact=True)
  889. (exp(-x), 1)
  890. The ``exact`` flag will also keep any unevaluated Muls from
  891. being evaluated:
  892. >>> u = Mul(2, x + 1, evaluate=False)
  893. >>> fraction(u)
  894. (2*x + 2, 1)
  895. >>> fraction(u, exact=True)
  896. (2*(x + 1), 1)
  897. """
  898. expr = sympify(expr)
  899. numer, denom = [], []
  900. for term in Mul.make_args(expr):
  901. if term.is_commutative and (term.is_Pow or isinstance(term, exp)):
  902. b, ex = term.as_base_exp()
  903. if ex.is_negative:
  904. if ex is S.NegativeOne:
  905. denom.append(b)
  906. elif exact:
  907. if ex.is_constant():
  908. denom.append(Pow(b, -ex))
  909. else:
  910. numer.append(term)
  911. else:
  912. denom.append(Pow(b, -ex))
  913. elif ex.is_positive:
  914. numer.append(term)
  915. elif not exact and ex.is_Mul:
  916. n, d = term.as_numer_denom()
  917. if n != 1:
  918. numer.append(n)
  919. denom.append(d)
  920. else:
  921. numer.append(term)
  922. elif term.is_Rational and not term.is_Integer:
  923. if term.p != 1:
  924. numer.append(term.p)
  925. denom.append(term.q)
  926. else:
  927. numer.append(term)
  928. return Mul(*numer, evaluate=not exact), Mul(*denom, evaluate=not exact)
  929. def numer(expr):
  930. return fraction(expr)[0]
  931. def denom(expr):
  932. return fraction(expr)[1]
  933. def fraction_expand(expr, **hints):
  934. return expr.expand(frac=True, **hints)
  935. def numer_expand(expr, **hints):
  936. a, b = fraction(expr)
  937. return a.expand(numer=True, **hints) / b
  938. def denom_expand(expr, **hints):
  939. a, b = fraction(expr)
  940. return a / b.expand(denom=True, **hints)
  941. expand_numer = numer_expand
  942. expand_denom = denom_expand
  943. expand_fraction = fraction_expand
  944. def split_surds(expr):
  945. """
  946. Split an expression with terms whose squares are positive rationals
  947. into a sum of terms whose surds squared have gcd equal to g
  948. and a sum of terms with surds squared prime with g.
  949. Examples
  950. ========
  951. >>> from sympy import sqrt
  952. >>> from sympy.simplify.radsimp import split_surds
  953. >>> split_surds(3*sqrt(3) + sqrt(5)/7 + sqrt(6) + sqrt(10) + sqrt(15))
  954. (3, sqrt(2) + sqrt(5) + 3, sqrt(5)/7 + sqrt(10))
  955. """
  956. args = sorted(expr.args, key=default_sort_key)
  957. coeff_muls = [x.as_coeff_Mul() for x in args]
  958. surds = [x[1]**2 for x in coeff_muls if x[1].is_Pow]
  959. surds.sort(key=default_sort_key)
  960. g, b1, b2 = _split_gcd(*surds)
  961. g2 = g
  962. if not b2 and len(b1) >= 2:
  963. b1n = [x/g for x in b1]
  964. b1n = [x for x in b1n if x != 1]
  965. # only a common factor has been factored; split again
  966. g1, b1n, b2 = _split_gcd(*b1n)
  967. g2 = g*g1
  968. a1v, a2v = [], []
  969. for c, s in coeff_muls:
  970. if s.is_Pow and s.exp == S.Half:
  971. s1 = s.base
  972. if s1 in b1:
  973. a1v.append(c*sqrt(s1/g2))
  974. else:
  975. a2v.append(c*s)
  976. else:
  977. a2v.append(c*s)
  978. a = Add(*a1v)
  979. b = Add(*a2v)
  980. return g2, a, b
  981. def _split_gcd(*a):
  982. """
  983. Split the list of integers ``a`` into a list of integers, ``a1`` having
  984. ``g = gcd(a1)``, and a list ``a2`` whose elements are not divisible by
  985. ``g``. Returns ``g, a1, a2``.
  986. Examples
  987. ========
  988. >>> from sympy.simplify.radsimp import _split_gcd
  989. >>> _split_gcd(55, 35, 22, 14, 77, 10)
  990. (5, [55, 35, 10], [22, 14, 77])
  991. """
  992. g = a[0]
  993. b1 = [g]
  994. b2 = []
  995. for x in a[1:]:
  996. g1 = gcd(g, x)
  997. if g1 == 1:
  998. b2.append(x)
  999. else:
  1000. g = g1
  1001. b1.append(x)
  1002. return g, b1, b2