rationaltools.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """Tools for manipulation of rational expressions. """
  2. from sympy.core import Basic, Add, sympify
  3. from sympy.core.exprtools import gcd_terms
  4. from sympy.utilities import public
  5. from sympy.utilities.iterables import iterable
  6. @public
  7. def together(expr, deep=False, fraction=True):
  8. """
  9. Denest and combine rational expressions using symbolic methods.
  10. This function takes an expression or a container of expressions
  11. and puts it (them) together by denesting and combining rational
  12. subexpressions. No heroic measures are taken to minimize degree
  13. of the resulting numerator and denominator. To obtain completely
  14. reduced expression use :func:`~.cancel`. However, :func:`~.together`
  15. can preserve as much as possible of the structure of the input
  16. expression in the output (no expansion is performed).
  17. A wide variety of objects can be put together including lists,
  18. tuples, sets, relational objects, integrals and others. It is
  19. also possible to transform interior of function applications,
  20. by setting ``deep`` flag to ``True``.
  21. By definition, :func:`~.together` is a complement to :func:`~.apart`,
  22. so ``apart(together(expr))`` should return expr unchanged. Note
  23. however, that :func:`~.together` uses only symbolic methods, so
  24. it might be necessary to use :func:`~.cancel` to perform algebraic
  25. simplification and minimize degree of the numerator and denominator.
  26. Examples
  27. ========
  28. >>> from sympy import together, exp
  29. >>> from sympy.abc import x, y, z
  30. >>> together(1/x + 1/y)
  31. (x + y)/(x*y)
  32. >>> together(1/x + 1/y + 1/z)
  33. (x*y + x*z + y*z)/(x*y*z)
  34. >>> together(1/(x*y) + 1/y**2)
  35. (x + y)/(x*y**2)
  36. >>> together(1/(1 + 1/x) + 1/(1 + 1/y))
  37. (x*(y + 1) + y*(x + 1))/((x + 1)*(y + 1))
  38. >>> together(exp(1/x + 1/y))
  39. exp(1/y + 1/x)
  40. >>> together(exp(1/x + 1/y), deep=True)
  41. exp((x + y)/(x*y))
  42. >>> together(1/exp(x) + 1/(x*exp(x)))
  43. (x + 1)*exp(-x)/x
  44. >>> together(1/exp(2*x) + 1/(x*exp(3*x)))
  45. (x*exp(x) + 1)*exp(-3*x)/x
  46. """
  47. def _together(expr):
  48. if isinstance(expr, Basic):
  49. if expr.is_Atom or (expr.is_Function and not deep):
  50. return expr
  51. elif expr.is_Add:
  52. return gcd_terms(list(map(_together, Add.make_args(expr))), fraction=fraction)
  53. elif expr.is_Pow:
  54. base = _together(expr.base)
  55. if deep:
  56. exp = _together(expr.exp)
  57. else:
  58. exp = expr.exp
  59. return expr.__class__(base, exp)
  60. else:
  61. return expr.__class__(*[ _together(arg) for arg in expr.args ])
  62. elif iterable(expr):
  63. return expr.__class__([ _together(ex) for ex in expr ])
  64. return expr
  65. return _together(sympify(expr))