radsimp.py 39 KB

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