图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4110 lines
137 KiB

  1. from typing import Tuple as tTuple
  2. from collections.abc import Iterable
  3. from functools import reduce
  4. from .sympify import sympify, _sympify
  5. from .basic import Basic, Atom
  6. from .singleton import S
  7. from .evalf import EvalfMixin, pure_complex, DEFAULT_MAXPREC
  8. from .decorators import call_highest_priority, sympify_method_args, sympify_return
  9. from .cache import cacheit
  10. from .sorting import default_sort_key
  11. from .kind import NumberKind
  12. from sympy.utilities.exceptions import sympy_deprecation_warning
  13. from sympy.utilities.misc import as_int, func_name, filldedent
  14. from sympy.utilities.iterables import has_variety, sift
  15. from mpmath.libmp import mpf_log, prec_to_dps
  16. from mpmath.libmp.libintmath import giant_steps
  17. from collections import defaultdict
  18. def _corem(eq, c): # helper for extract_additively
  19. # return co, diff from co*c + diff
  20. co = []
  21. non = []
  22. for i in Add.make_args(eq):
  23. ci = i.coeff(c)
  24. if not ci:
  25. non.append(i)
  26. else:
  27. co.append(ci)
  28. return Add(*co), Add(*non)
  29. @sympify_method_args
  30. class Expr(Basic, EvalfMixin):
  31. """
  32. Base class for algebraic expressions.
  33. Explanation
  34. ===========
  35. Everything that requires arithmetic operations to be defined
  36. should subclass this class, instead of Basic (which should be
  37. used only for argument storage and expression manipulation, i.e.
  38. pattern matching, substitutions, etc).
  39. If you want to override the comparisons of expressions:
  40. Should use _eval_is_ge for inequality, or _eval_is_eq, with multiple dispatch.
  41. _eval_is_ge return true if x >= y, false if x < y, and None if the two types
  42. are not comparable or the comparison is indeterminate
  43. See Also
  44. ========
  45. sympy.core.basic.Basic
  46. """
  47. __slots__ = () # type: tTuple[str, ...]
  48. is_scalar = True # self derivative is 1
  49. @property
  50. def _diff_wrt(self):
  51. """Return True if one can differentiate with respect to this
  52. object, else False.
  53. Explanation
  54. ===========
  55. Subclasses such as Symbol, Function and Derivative return True
  56. to enable derivatives wrt them. The implementation in Derivative
  57. separates the Symbol and non-Symbol (_diff_wrt=True) variables and
  58. temporarily converts the non-Symbols into Symbols when performing
  59. the differentiation. By default, any object deriving from Expr
  60. will behave like a scalar with self.diff(self) == 1. If this is
  61. not desired then the object must also set `is_scalar = False` or
  62. else define an _eval_derivative routine.
  63. Note, see the docstring of Derivative for how this should work
  64. mathematically. In particular, note that expr.subs(yourclass, Symbol)
  65. should be well-defined on a structural level, or this will lead to
  66. inconsistent results.
  67. Examples
  68. ========
  69. >>> from sympy import Expr
  70. >>> e = Expr()
  71. >>> e._diff_wrt
  72. False
  73. >>> class MyScalar(Expr):
  74. ... _diff_wrt = True
  75. ...
  76. >>> MyScalar().diff(MyScalar())
  77. 1
  78. >>> class MySymbol(Expr):
  79. ... _diff_wrt = True
  80. ... is_scalar = False
  81. ...
  82. >>> MySymbol().diff(MySymbol())
  83. Derivative(MySymbol(), MySymbol())
  84. """
  85. return False
  86. @cacheit
  87. def sort_key(self, order=None):
  88. coeff, expr = self.as_coeff_Mul()
  89. if expr.is_Pow:
  90. if expr.base is S.Exp1:
  91. # If we remove this, many doctests will go crazy:
  92. # (keeps E**x sorted like the exp(x) function,
  93. # part of exp(x) to E**x transition)
  94. expr, exp = Function("exp")(expr.exp), S.One
  95. else:
  96. expr, exp = expr.args
  97. else:
  98. exp = S.One
  99. if expr.is_Dummy:
  100. args = (expr.sort_key(),)
  101. elif expr.is_Atom:
  102. args = (str(expr),)
  103. else:
  104. if expr.is_Add:
  105. args = expr.as_ordered_terms(order=order)
  106. elif expr.is_Mul:
  107. args = expr.as_ordered_factors(order=order)
  108. else:
  109. args = expr.args
  110. args = tuple(
  111. [ default_sort_key(arg, order=order) for arg in args ])
  112. args = (len(args), tuple(args))
  113. exp = exp.sort_key(order=order)
  114. return expr.class_key(), args, exp, coeff
  115. def _hashable_content(self):
  116. """Return a tuple of information about self that can be used to
  117. compute the hash. If a class defines additional attributes,
  118. like ``name`` in Symbol, then this method should be updated
  119. accordingly to return such relevant attributes.
  120. Defining more than _hashable_content is necessary if __eq__ has
  121. been defined by a class. See note about this in Basic.__eq__."""
  122. return self._args
  123. # ***************
  124. # * Arithmetics *
  125. # ***************
  126. # Expr and its sublcasses use _op_priority to determine which object
  127. # passed to a binary special method (__mul__, etc.) will handle the
  128. # operation. In general, the 'call_highest_priority' decorator will choose
  129. # the object with the highest _op_priority to handle the call.
  130. # Custom subclasses that want to define their own binary special methods
  131. # should set an _op_priority value that is higher than the default.
  132. #
  133. # **NOTE**:
  134. # This is a temporary fix, and will eventually be replaced with
  135. # something better and more powerful. See issue 5510.
  136. _op_priority = 10.0
  137. @property
  138. def _add_handler(self):
  139. return Add
  140. @property
  141. def _mul_handler(self):
  142. return Mul
  143. def __pos__(self):
  144. return self
  145. def __neg__(self):
  146. # Mul has its own __neg__ routine, so we just
  147. # create a 2-args Mul with the -1 in the canonical
  148. # slot 0.
  149. c = self.is_commutative
  150. return Mul._from_args((S.NegativeOne, self), c)
  151. def __abs__(self):
  152. from sympy.functions.elementary.complexes import Abs
  153. return Abs(self)
  154. @sympify_return([('other', 'Expr')], NotImplemented)
  155. @call_highest_priority('__radd__')
  156. def __add__(self, other):
  157. return Add(self, other)
  158. @sympify_return([('other', 'Expr')], NotImplemented)
  159. @call_highest_priority('__add__')
  160. def __radd__(self, other):
  161. return Add(other, self)
  162. @sympify_return([('other', 'Expr')], NotImplemented)
  163. @call_highest_priority('__rsub__')
  164. def __sub__(self, other):
  165. return Add(self, -other)
  166. @sympify_return([('other', 'Expr')], NotImplemented)
  167. @call_highest_priority('__sub__')
  168. def __rsub__(self, other):
  169. return Add(other, -self)
  170. @sympify_return([('other', 'Expr')], NotImplemented)
  171. @call_highest_priority('__rmul__')
  172. def __mul__(self, other):
  173. return Mul(self, other)
  174. @sympify_return([('other', 'Expr')], NotImplemented)
  175. @call_highest_priority('__mul__')
  176. def __rmul__(self, other):
  177. return Mul(other, self)
  178. @sympify_return([('other', 'Expr')], NotImplemented)
  179. @call_highest_priority('__rpow__')
  180. def _pow(self, other):
  181. return Pow(self, other)
  182. def __pow__(self, other, mod=None):
  183. if mod is None:
  184. return self._pow(other)
  185. try:
  186. _self, other, mod = as_int(self), as_int(other), as_int(mod)
  187. if other >= 0:
  188. return pow(_self, other, mod)
  189. else:
  190. from sympy.core.numbers import mod_inverse
  191. return mod_inverse(pow(_self, -other, mod), mod)
  192. except ValueError:
  193. power = self._pow(other)
  194. try:
  195. return power%mod
  196. except TypeError:
  197. return NotImplemented
  198. @sympify_return([('other', 'Expr')], NotImplemented)
  199. @call_highest_priority('__pow__')
  200. def __rpow__(self, other):
  201. return Pow(other, self)
  202. @sympify_return([('other', 'Expr')], NotImplemented)
  203. @call_highest_priority('__rtruediv__')
  204. def __truediv__(self, other):
  205. denom = Pow(other, S.NegativeOne)
  206. if self is S.One:
  207. return denom
  208. else:
  209. return Mul(self, denom)
  210. @sympify_return([('other', 'Expr')], NotImplemented)
  211. @call_highest_priority('__truediv__')
  212. def __rtruediv__(self, other):
  213. denom = Pow(self, S.NegativeOne)
  214. if other is S.One:
  215. return denom
  216. else:
  217. return Mul(other, denom)
  218. @sympify_return([('other', 'Expr')], NotImplemented)
  219. @call_highest_priority('__rmod__')
  220. def __mod__(self, other):
  221. return Mod(self, other)
  222. @sympify_return([('other', 'Expr')], NotImplemented)
  223. @call_highest_priority('__mod__')
  224. def __rmod__(self, other):
  225. return Mod(other, self)
  226. @sympify_return([('other', 'Expr')], NotImplemented)
  227. @call_highest_priority('__rfloordiv__')
  228. def __floordiv__(self, other):
  229. from sympy.functions.elementary.integers import floor
  230. return floor(self / other)
  231. @sympify_return([('other', 'Expr')], NotImplemented)
  232. @call_highest_priority('__floordiv__')
  233. def __rfloordiv__(self, other):
  234. from sympy.functions.elementary.integers import floor
  235. return floor(other / self)
  236. @sympify_return([('other', 'Expr')], NotImplemented)
  237. @call_highest_priority('__rdivmod__')
  238. def __divmod__(self, other):
  239. from sympy.functions.elementary.integers import floor
  240. return floor(self / other), Mod(self, other)
  241. @sympify_return([('other', 'Expr')], NotImplemented)
  242. @call_highest_priority('__divmod__')
  243. def __rdivmod__(self, other):
  244. from sympy.functions.elementary.integers import floor
  245. return floor(other / self), Mod(other, self)
  246. def __int__(self):
  247. # Although we only need to round to the units position, we'll
  248. # get one more digit so the extra testing below can be avoided
  249. # unless the rounded value rounded to an integer, e.g. if an
  250. # expression were equal to 1.9 and we rounded to the unit position
  251. # we would get a 2 and would not know if this rounded up or not
  252. # without doing a test (as done below). But if we keep an extra
  253. # digit we know that 1.9 is not the same as 1 and there is no
  254. # need for further testing: our int value is correct. If the value
  255. # were 1.99, however, this would round to 2.0 and our int value is
  256. # off by one. So...if our round value is the same as the int value
  257. # (regardless of how much extra work we do to calculate extra decimal
  258. # places) we need to test whether we are off by one.
  259. from .symbol import Dummy
  260. if not self.is_number:
  261. raise TypeError("Cannot convert symbols to int")
  262. r = self.round(2)
  263. if not r.is_Number:
  264. raise TypeError("Cannot convert complex to int")
  265. if r in (S.NaN, S.Infinity, S.NegativeInfinity):
  266. raise TypeError("Cannot convert %s to int" % r)
  267. i = int(r)
  268. if not i:
  269. return 0
  270. # off-by-one check
  271. if i == r and not (self - i).equals(0):
  272. isign = 1 if i > 0 else -1
  273. x = Dummy()
  274. # in the following (self - i).evalf(2) will not always work while
  275. # (self - r).evalf(2) and the use of subs does; if the test that
  276. # was added when this comment was added passes, it might be safe
  277. # to simply use sign to compute this rather than doing this by hand:
  278. diff_sign = 1 if (self - x).evalf(2, subs={x: i}) > 0 else -1
  279. if diff_sign != isign:
  280. i -= isign
  281. return i
  282. def __float__(self):
  283. # Don't bother testing if it's a number; if it's not this is going
  284. # to fail, and if it is we still need to check that it evalf'ed to
  285. # a number.
  286. result = self.evalf()
  287. if result.is_Number:
  288. return float(result)
  289. if result.is_number and result.as_real_imag()[1]:
  290. raise TypeError("Cannot convert complex to float")
  291. raise TypeError("Cannot convert expression to float")
  292. def __complex__(self):
  293. result = self.evalf()
  294. re, im = result.as_real_imag()
  295. return complex(float(re), float(im))
  296. @sympify_return([('other', 'Expr')], NotImplemented)
  297. def __ge__(self, other):
  298. from .relational import GreaterThan
  299. return GreaterThan(self, other)
  300. @sympify_return([('other', 'Expr')], NotImplemented)
  301. def __le__(self, other):
  302. from .relational import LessThan
  303. return LessThan(self, other)
  304. @sympify_return([('other', 'Expr')], NotImplemented)
  305. def __gt__(self, other):
  306. from .relational import StrictGreaterThan
  307. return StrictGreaterThan(self, other)
  308. @sympify_return([('other', 'Expr')], NotImplemented)
  309. def __lt__(self, other):
  310. from .relational import StrictLessThan
  311. return StrictLessThan(self, other)
  312. def __trunc__(self):
  313. if not self.is_number:
  314. raise TypeError("Cannot truncate symbols and expressions")
  315. else:
  316. return Integer(self)
  317. @staticmethod
  318. def _from_mpmath(x, prec):
  319. from .numbers import Float
  320. if hasattr(x, "_mpf_"):
  321. return Float._new(x._mpf_, prec)
  322. elif hasattr(x, "_mpc_"):
  323. re, im = x._mpc_
  324. re = Float._new(re, prec)
  325. im = Float._new(im, prec)*S.ImaginaryUnit
  326. return re + im
  327. else:
  328. raise TypeError("expected mpmath number (mpf or mpc)")
  329. @property
  330. def is_number(self):
  331. """Returns True if ``self`` has no free symbols and no
  332. undefined functions (AppliedUndef, to be precise). It will be
  333. faster than ``if not self.free_symbols``, however, since
  334. ``is_number`` will fail as soon as it hits a free symbol
  335. or undefined function.
  336. Examples
  337. ========
  338. >>> from sympy import Function, Integral, cos, sin, pi
  339. >>> from sympy.abc import x
  340. >>> f = Function('f')
  341. >>> x.is_number
  342. False
  343. >>> f(1).is_number
  344. False
  345. >>> (2*x).is_number
  346. False
  347. >>> (2 + Integral(2, x)).is_number
  348. False
  349. >>> (2 + Integral(2, (x, 1, 2))).is_number
  350. True
  351. Not all numbers are Numbers in the SymPy sense:
  352. >>> pi.is_number, pi.is_Number
  353. (True, False)
  354. If something is a number it should evaluate to a number with
  355. real and imaginary parts that are Numbers; the result may not
  356. be comparable, however, since the real and/or imaginary part
  357. of the result may not have precision.
  358. >>> cos(1).is_number and cos(1).is_comparable
  359. True
  360. >>> z = cos(1)**2 + sin(1)**2 - 1
  361. >>> z.is_number
  362. True
  363. >>> z.is_comparable
  364. False
  365. See Also
  366. ========
  367. sympy.core.basic.Basic.is_comparable
  368. """
  369. return all(obj.is_number for obj in self.args)
  370. def _random(self, n=None, re_min=-1, im_min=-1, re_max=1, im_max=1):
  371. """Return self evaluated, if possible, replacing free symbols with
  372. random complex values, if necessary.
  373. Explanation
  374. ===========
  375. The random complex value for each free symbol is generated
  376. by the random_complex_number routine giving real and imaginary
  377. parts in the range given by the re_min, re_max, im_min, and im_max
  378. values. The returned value is evaluated to a precision of n
  379. (if given) else the maximum of 15 and the precision needed
  380. to get more than 1 digit of precision. If the expression
  381. could not be evaluated to a number, or could not be evaluated
  382. to more than 1 digit of precision, then None is returned.
  383. Examples
  384. ========
  385. >>> from sympy import sqrt
  386. >>> from sympy.abc import x, y
  387. >>> x._random() # doctest: +SKIP
  388. 0.0392918155679172 + 0.916050214307199*I
  389. >>> x._random(2) # doctest: +SKIP
  390. -0.77 - 0.87*I
  391. >>> (x + y/2)._random(2) # doctest: +SKIP
  392. -0.57 + 0.16*I
  393. >>> sqrt(2)._random(2)
  394. 1.4
  395. See Also
  396. ========
  397. sympy.core.random.random_complex_number
  398. """
  399. free = self.free_symbols
  400. prec = 1
  401. if free:
  402. from sympy.core.random import random_complex_number
  403. a, c, b, d = re_min, re_max, im_min, im_max
  404. reps = dict(list(zip(free, [random_complex_number(a, b, c, d, rational=True)
  405. for zi in free])))
  406. try:
  407. nmag = abs(self.evalf(2, subs=reps))
  408. except (ValueError, TypeError):
  409. # if an out of range value resulted in evalf problems
  410. # then return None -- XXX is there a way to know how to
  411. # select a good random number for a given expression?
  412. # e.g. when calculating n! negative values for n should not
  413. # be used
  414. return None
  415. else:
  416. reps = {}
  417. nmag = abs(self.evalf(2))
  418. if not hasattr(nmag, '_prec'):
  419. # e.g. exp_polar(2*I*pi) doesn't evaluate but is_number is True
  420. return None
  421. if nmag._prec == 1:
  422. # increase the precision up to the default maximum
  423. # precision to see if we can get any significance
  424. # evaluate
  425. for prec in giant_steps(2, DEFAULT_MAXPREC):
  426. nmag = abs(self.evalf(prec, subs=reps))
  427. if nmag._prec != 1:
  428. break
  429. if nmag._prec != 1:
  430. if n is None:
  431. n = max(prec, 15)
  432. return self.evalf(n, subs=reps)
  433. # never got any significance
  434. return None
  435. def is_constant(self, *wrt, **flags):
  436. """Return True if self is constant, False if not, or None if
  437. the constancy could not be determined conclusively.
  438. Explanation
  439. ===========
  440. If an expression has no free symbols then it is a constant. If
  441. there are free symbols it is possible that the expression is a
  442. constant, perhaps (but not necessarily) zero. To test such
  443. expressions, a few strategies are tried:
  444. 1) numerical evaluation at two random points. If two such evaluations
  445. give two different values and the values have a precision greater than
  446. 1 then self is not constant. If the evaluations agree or could not be
  447. obtained with any precision, no decision is made. The numerical testing
  448. is done only if ``wrt`` is different than the free symbols.
  449. 2) differentiation with respect to variables in 'wrt' (or all free
  450. symbols if omitted) to see if the expression is constant or not. This
  451. will not always lead to an expression that is zero even though an
  452. expression is constant (see added test in test_expr.py). If
  453. all derivatives are zero then self is constant with respect to the
  454. given symbols.
  455. 3) finding out zeros of denominator expression with free_symbols.
  456. It will not be constant if there are zeros. It gives more negative
  457. answers for expression that are not constant.
  458. If neither evaluation nor differentiation can prove the expression is
  459. constant, None is returned unless two numerical values happened to be
  460. the same and the flag ``failing_number`` is True -- in that case the
  461. numerical value will be returned.
  462. If flag simplify=False is passed, self will not be simplified;
  463. the default is True since self should be simplified before testing.
  464. Examples
  465. ========
  466. >>> from sympy import cos, sin, Sum, S, pi
  467. >>> from sympy.abc import a, n, x, y
  468. >>> x.is_constant()
  469. False
  470. >>> S(2).is_constant()
  471. True
  472. >>> Sum(x, (x, 1, 10)).is_constant()
  473. True
  474. >>> Sum(x, (x, 1, n)).is_constant()
  475. False
  476. >>> Sum(x, (x, 1, n)).is_constant(y)
  477. True
  478. >>> Sum(x, (x, 1, n)).is_constant(n)
  479. False
  480. >>> Sum(x, (x, 1, n)).is_constant(x)
  481. True
  482. >>> eq = a*cos(x)**2 + a*sin(x)**2 - a
  483. >>> eq.is_constant()
  484. True
  485. >>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
  486. True
  487. >>> (0**x).is_constant()
  488. False
  489. >>> x.is_constant()
  490. False
  491. >>> (x**x).is_constant()
  492. False
  493. >>> one = cos(x)**2 + sin(x)**2
  494. >>> one.is_constant()
  495. True
  496. >>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
  497. True
  498. """
  499. def check_denominator_zeros(expression):
  500. from sympy.solvers.solvers import denoms
  501. retNone = False
  502. for den in denoms(expression):
  503. z = den.is_zero
  504. if z is True:
  505. return True
  506. if z is None:
  507. retNone = True
  508. if retNone:
  509. return None
  510. return False
  511. simplify = flags.get('simplify', True)
  512. if self.is_number:
  513. return True
  514. free = self.free_symbols
  515. if not free:
  516. return True # assume f(1) is some constant
  517. # if we are only interested in some symbols and they are not in the
  518. # free symbols then this expression is constant wrt those symbols
  519. wrt = set(wrt)
  520. if wrt and not wrt & free:
  521. return True
  522. wrt = wrt or free
  523. # simplify unless this has already been done
  524. expr = self
  525. if simplify:
  526. expr = expr.simplify()
  527. # is_zero should be a quick assumptions check; it can be wrong for
  528. # numbers (see test_is_not_constant test), giving False when it
  529. # shouldn't, but hopefully it will never give True unless it is sure.
  530. if expr.is_zero:
  531. return True
  532. # Don't attempt substitution or differentiation with non-number symbols
  533. wrt_number = {sym for sym in wrt if sym.kind is NumberKind}
  534. # try numerical evaluation to see if we get two different values
  535. failing_number = None
  536. if wrt_number == free:
  537. # try 0 (for a) and 1 (for b)
  538. try:
  539. a = expr.subs(list(zip(free, [0]*len(free))),
  540. simultaneous=True)
  541. if a is S.NaN:
  542. # evaluation may succeed when substitution fails
  543. a = expr._random(None, 0, 0, 0, 0)
  544. except ZeroDivisionError:
  545. a = None
  546. if a is not None and a is not S.NaN:
  547. try:
  548. b = expr.subs(list(zip(free, [1]*len(free))),
  549. simultaneous=True)
  550. if b is S.NaN:
  551. # evaluation may succeed when substitution fails
  552. b = expr._random(None, 1, 0, 1, 0)
  553. except ZeroDivisionError:
  554. b = None
  555. if b is not None and b is not S.NaN and b.equals(a) is False:
  556. return False
  557. # try random real
  558. b = expr._random(None, -1, 0, 1, 0)
  559. if b is not None and b is not S.NaN and b.equals(a) is False:
  560. return False
  561. # try random complex
  562. b = expr._random()
  563. if b is not None and b is not S.NaN:
  564. if b.equals(a) is False:
  565. return False
  566. failing_number = a if a.is_number else b
  567. # now we will test each wrt symbol (or all free symbols) to see if the
  568. # expression depends on them or not using differentiation. This is
  569. # not sufficient for all expressions, however, so we don't return
  570. # False if we get a derivative other than 0 with free symbols.
  571. for w in wrt_number:
  572. deriv = expr.diff(w)
  573. if simplify:
  574. deriv = deriv.simplify()
  575. if deriv != 0:
  576. if not (pure_complex(deriv, or_real=True)):
  577. if flags.get('failing_number', False):
  578. return failing_number
  579. return False
  580. cd = check_denominator_zeros(self)
  581. if cd is True:
  582. return False
  583. elif cd is None:
  584. return None
  585. return True
  586. def equals(self, other, failing_expression=False):
  587. """Return True if self == other, False if it doesn't, or None. If
  588. failing_expression is True then the expression which did not simplify
  589. to a 0 will be returned instead of None.
  590. Explanation
  591. ===========
  592. If ``self`` is a Number (or complex number) that is not zero, then
  593. the result is False.
  594. If ``self`` is a number and has not evaluated to zero, evalf will be
  595. used to test whether the expression evaluates to zero. If it does so
  596. and the result has significance (i.e. the precision is either -1, for
  597. a Rational result, or is greater than 1) then the evalf value will be
  598. used to return True or False.
  599. """
  600. from sympy.simplify.simplify import nsimplify, simplify
  601. from sympy.solvers.solvers import solve
  602. from sympy.polys.polyerrors import NotAlgebraic
  603. from sympy.polys.numberfields import minimal_polynomial
  604. other = sympify(other)
  605. if self == other:
  606. return True
  607. # they aren't the same so see if we can make the difference 0;
  608. # don't worry about doing simplification steps one at a time
  609. # because if the expression ever goes to 0 then the subsequent
  610. # simplification steps that are done will be very fast.
  611. diff = factor_terms(simplify(self - other), radical=True)
  612. if not diff:
  613. return True
  614. if not diff.has(Add, Mod):
  615. # if there is no expanding to be done after simplifying
  616. # then this can't be a zero
  617. return False
  618. factors = diff.as_coeff_mul()[1]
  619. if len(factors) > 1: # avoid infinity recursion
  620. fac_zero = [fac.equals(0) for fac in factors]
  621. if None not in fac_zero: # every part can be decided
  622. return any(fac_zero)
  623. constant = diff.is_constant(simplify=False, failing_number=True)
  624. if constant is False:
  625. return False
  626. if not diff.is_number:
  627. if constant is None:
  628. # e.g. unless the right simplification is done, a symbolic
  629. # zero is possible (see expression of issue 6829: without
  630. # simplification constant will be None).
  631. return
  632. if constant is True:
  633. # this gives a number whether there are free symbols or not
  634. ndiff = diff._random()
  635. # is_comparable will work whether the result is real
  636. # or complex; it could be None, however.
  637. if ndiff and ndiff.is_comparable:
  638. return False
  639. # sometimes we can use a simplified result to give a clue as to
  640. # what the expression should be; if the expression is *not* zero
  641. # then we should have been able to compute that and so now
  642. # we can just consider the cases where the approximation appears
  643. # to be zero -- we try to prove it via minimal_polynomial.
  644. #
  645. # removed
  646. # ns = nsimplify(diff)
  647. # if diff.is_number and (not ns or ns == diff):
  648. #
  649. # The thought was that if it nsimplifies to 0 that's a sure sign
  650. # to try the following to prove it; or if it changed but wasn't
  651. # zero that might be a sign that it's not going to be easy to
  652. # prove. But tests seem to be working without that logic.
  653. #
  654. if diff.is_number:
  655. # try to prove via self-consistency
  656. surds = [s for s in diff.atoms(Pow) if s.args[0].is_Integer]
  657. # it seems to work better to try big ones first
  658. surds.sort(key=lambda x: -x.args[0])
  659. for s in surds:
  660. try:
  661. # simplify is False here -- this expression has already
  662. # been identified as being hard to identify as zero;
  663. # we will handle the checking ourselves using nsimplify
  664. # to see if we are in the right ballpark or not and if so
  665. # *then* the simplification will be attempted.
  666. sol = solve(diff, s, simplify=False)
  667. if sol:
  668. if s in sol:
  669. # the self-consistent result is present
  670. return True
  671. if all(si.is_Integer for si in sol):
  672. # perfect powers are removed at instantiation
  673. # so surd s cannot be an integer
  674. return False
  675. if all(i.is_algebraic is False for i in sol):
  676. # a surd is algebraic
  677. return False
  678. if any(si in surds for si in sol):
  679. # it wasn't equal to s but it is in surds
  680. # and different surds are not equal
  681. return False
  682. if any(nsimplify(s - si) == 0 and
  683. simplify(s - si) == 0 for si in sol):
  684. return True
  685. if s.is_real:
  686. if any(nsimplify(si, [s]) == s and simplify(si) == s
  687. for si in sol):
  688. return True
  689. except NotImplementedError:
  690. pass
  691. # try to prove with minimal_polynomial but know when
  692. # *not* to use this or else it can take a long time. e.g. issue 8354
  693. if True: # change True to condition that assures non-hang
  694. try:
  695. mp = minimal_polynomial(diff)
  696. if mp.is_Symbol:
  697. return True
  698. return False
  699. except (NotAlgebraic, NotImplementedError):
  700. pass
  701. # diff has not simplified to zero; constant is either None, True
  702. # or the number with significance (is_comparable) that was randomly
  703. # calculated twice as the same value.
  704. if constant not in (True, None) and constant != 0:
  705. return False
  706. if failing_expression:
  707. return diff
  708. return None
  709. def _eval_is_positive(self):
  710. finite = self.is_finite
  711. if finite is False:
  712. return False
  713. extended_positive = self.is_extended_positive
  714. if finite is True:
  715. return extended_positive
  716. if extended_positive is False:
  717. return False
  718. def _eval_is_negative(self):
  719. finite = self.is_finite
  720. if finite is False:
  721. return False
  722. extended_negative = self.is_extended_negative
  723. if finite is True:
  724. return extended_negative
  725. if extended_negative is False:
  726. return False
  727. def _eval_is_extended_positive_negative(self, positive):
  728. from sympy.polys.numberfields import minimal_polynomial
  729. from sympy.polys.polyerrors import NotAlgebraic
  730. if self.is_number:
  731. if self.is_extended_real is False:
  732. return False
  733. # check to see that we can get a value
  734. try:
  735. n2 = self._eval_evalf(2)
  736. # XXX: This shouldn't be caught here
  737. # Catches ValueError: hypsum() failed to converge to the requested
  738. # 34 bits of accuracy
  739. except ValueError:
  740. return None
  741. if n2 is None:
  742. return None
  743. if getattr(n2, '_prec', 1) == 1: # no significance
  744. return None
  745. if n2 is S.NaN:
  746. return None
  747. f = self.evalf(2)
  748. if f.is_Float:
  749. match = f, S.Zero
  750. else:
  751. match = pure_complex(f)
  752. if match is None:
  753. return False
  754. r, i = match
  755. if not (i.is_Number and r.is_Number):
  756. return False
  757. if r._prec != 1 and i._prec != 1:
  758. return bool(not i and ((r > 0) if positive else (r < 0)))
  759. elif r._prec == 1 and (not i or i._prec == 1) and \
  760. self.is_algebraic and not self.has(Function):
  761. try:
  762. if minimal_polynomial(self).is_Symbol:
  763. return False
  764. except (NotAlgebraic, NotImplementedError):
  765. pass
  766. def _eval_is_extended_positive(self):
  767. return self._eval_is_extended_positive_negative(positive=True)
  768. def _eval_is_extended_negative(self):
  769. return self._eval_is_extended_positive_negative(positive=False)
  770. def _eval_interval(self, x, a, b):
  771. """
  772. Returns evaluation over an interval. For most functions this is:
  773. self.subs(x, b) - self.subs(x, a),
  774. possibly using limit() if NaN is returned from subs, or if
  775. singularities are found between a and b.
  776. If b or a is None, it only evaluates -self.subs(x, a) or self.subs(b, x),
  777. respectively.
  778. """
  779. from sympy.calculus.accumulationbounds import AccumBounds
  780. from sympy.functions.elementary.exponential import log
  781. from sympy.series.limits import limit, Limit
  782. from sympy.sets.sets import Interval
  783. from sympy.solvers.solveset import solveset
  784. if (a is None and b is None):
  785. raise ValueError('Both interval ends cannot be None.')
  786. def _eval_endpoint(left):
  787. c = a if left else b
  788. if c is None:
  789. return S.Zero
  790. else:
  791. C = self.subs(x, c)
  792. if C.has(S.NaN, S.Infinity, S.NegativeInfinity,
  793. S.ComplexInfinity, AccumBounds):
  794. if (a < b) != False:
  795. C = limit(self, x, c, "+" if left else "-")
  796. else:
  797. C = limit(self, x, c, "-" if left else "+")
  798. if isinstance(C, Limit):
  799. raise NotImplementedError("Could not compute limit")
  800. return C
  801. if a == b:
  802. return S.Zero
  803. A = _eval_endpoint(left=True)
  804. if A is S.NaN:
  805. return A
  806. B = _eval_endpoint(left=False)
  807. if (a and b) is None:
  808. return B - A
  809. value = B - A
  810. if a.is_comparable and b.is_comparable:
  811. if a < b:
  812. domain = Interval(a, b)
  813. else:
  814. domain = Interval(b, a)
  815. # check the singularities of self within the interval
  816. # if singularities is a ConditionSet (not iterable), catch the exception and pass
  817. singularities = solveset(self.cancel().as_numer_denom()[1], x,
  818. domain=domain)
  819. for logterm in self.atoms(log):
  820. singularities = singularities | solveset(logterm.args[0], x,
  821. domain=domain)
  822. try:
  823. for s in singularities:
  824. if value is S.NaN:
  825. # no need to keep adding, it will stay NaN
  826. break
  827. if not s.is_comparable:
  828. continue
  829. if (a < s) == (s < b) == True:
  830. value += -limit(self, x, s, "+") + limit(self, x, s, "-")
  831. elif (b < s) == (s < a) == True:
  832. value += limit(self, x, s, "+") - limit(self, x, s, "-")
  833. except TypeError:
  834. pass
  835. return value
  836. def _eval_power(self, other):
  837. # subclass to compute self**other for cases when
  838. # other is not NaN, 0, or 1
  839. return None
  840. def _eval_conjugate(self):
  841. if self.is_extended_real:
  842. return self
  843. elif self.is_imaginary:
  844. return -self
  845. def conjugate(self):
  846. """Returns the complex conjugate of 'self'."""
  847. from sympy.functions.elementary.complexes import conjugate as c
  848. return c(self)
  849. def dir(self, x, cdir):
  850. if self.is_zero:
  851. return S.Zero
  852. from sympy.functions.elementary.exponential import log
  853. minexp = S.Zero
  854. arg = self
  855. while arg:
  856. minexp += S.One
  857. arg = arg.diff(x)
  858. coeff = arg.subs(x, 0)
  859. if coeff is S.NaN:
  860. coeff = arg.limit(x, 0)
  861. if coeff is S.ComplexInfinity:
  862. try:
  863. coeff, _ = arg.leadterm(x)
  864. if coeff.has(log(x)):
  865. raise ValueError()
  866. except ValueError:
  867. coeff = arg.limit(x, 0)
  868. if coeff != S.Zero:
  869. break
  870. return coeff*cdir**minexp
  871. def _eval_transpose(self):
  872. from sympy.functions.elementary.complexes import conjugate
  873. if (self.is_complex or self.is_infinite):
  874. return self
  875. elif self.is_hermitian:
  876. return conjugate(self)
  877. elif self.is_antihermitian:
  878. return -conjugate(self)
  879. def transpose(self):
  880. from sympy.functions.elementary.complexes import transpose
  881. return transpose(self)
  882. def _eval_adjoint(self):
  883. from sympy.functions.elementary.complexes import conjugate, transpose
  884. if self.is_hermitian:
  885. return self
  886. elif self.is_antihermitian:
  887. return -self
  888. obj = self._eval_conjugate()
  889. if obj is not None:
  890. return transpose(obj)
  891. obj = self._eval_transpose()
  892. if obj is not None:
  893. return conjugate(obj)
  894. def adjoint(self):
  895. from sympy.functions.elementary.complexes import adjoint
  896. return adjoint(self)
  897. @classmethod
  898. def _parse_order(cls, order):
  899. """Parse and configure the ordering of terms. """
  900. from sympy.polys.orderings import monomial_key
  901. startswith = getattr(order, "startswith", None)
  902. if startswith is None:
  903. reverse = False
  904. else:
  905. reverse = startswith('rev-')
  906. if reverse:
  907. order = order[4:]
  908. monom_key = monomial_key(order)
  909. def neg(monom):
  910. result = []
  911. for m in monom:
  912. if isinstance(m, tuple):
  913. result.append(neg(m))
  914. else:
  915. result.append(-m)
  916. return tuple(result)
  917. def key(term):
  918. _, ((re, im), monom, ncpart) = term
  919. monom = neg(monom_key(monom))
  920. ncpart = tuple([e.sort_key(order=order) for e in ncpart])
  921. coeff = ((bool(im), im), (re, im))
  922. return monom, ncpart, coeff
  923. return key, reverse
  924. def as_ordered_factors(self, order=None):
  925. """Return list of ordered factors (if Mul) else [self]."""
  926. return [self]
  927. def as_poly(self, *gens, **args):
  928. """Converts ``self`` to a polynomial or returns ``None``.
  929. Explanation
  930. ===========
  931. >>> from sympy import sin
  932. >>> from sympy.abc import x, y
  933. >>> print((x**2 + x*y).as_poly())
  934. Poly(x**2 + x*y, x, y, domain='ZZ')
  935. >>> print((x**2 + x*y).as_poly(x, y))
  936. Poly(x**2 + x*y, x, y, domain='ZZ')
  937. >>> print((x**2 + sin(y)).as_poly(x, y))
  938. None
  939. """
  940. from sympy.polys.polyerrors import PolynomialError, GeneratorsNeeded
  941. from sympy.polys.polytools import Poly
  942. try:
  943. poly = Poly(self, *gens, **args)
  944. if not poly.is_Poly:
  945. return None
  946. else:
  947. return poly
  948. except (PolynomialError, GeneratorsNeeded):
  949. # PolynomialError is caught for e.g. exp(x).as_poly(x)
  950. # GeneratorsNeeded is caught for e.g. S(2).as_poly()
  951. return None
  952. def as_ordered_terms(self, order=None, data=False):
  953. """
  954. Transform an expression to an ordered list of terms.
  955. Examples
  956. ========
  957. >>> from sympy import sin, cos
  958. >>> from sympy.abc import x
  959. >>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
  960. [sin(x)**2*cos(x), sin(x)**2, 1]
  961. """
  962. from .numbers import Number, NumberSymbol
  963. if order is None and self.is_Add:
  964. # Spot the special case of Add(Number, Mul(Number, expr)) with the
  965. # first number positive and the second number negative
  966. key = lambda x:not isinstance(x, (Number, NumberSymbol))
  967. add_args = sorted(Add.make_args(self), key=key)
  968. if (len(add_args) == 2
  969. and isinstance(add_args[0], (Number, NumberSymbol))
  970. and isinstance(add_args[1], Mul)):
  971. mul_args = sorted(Mul.make_args(add_args[1]), key=key)
  972. if (len(mul_args) == 2
  973. and isinstance(mul_args[0], Number)
  974. and add_args[0].is_positive
  975. and mul_args[0].is_negative):
  976. return add_args
  977. key, reverse = self._parse_order(order)
  978. terms, gens = self.as_terms()
  979. if not any(term.is_Order for term, _ in terms):
  980. ordered = sorted(terms, key=key, reverse=reverse)
  981. else:
  982. _terms, _order = [], []
  983. for term, repr in terms:
  984. if not term.is_Order:
  985. _terms.append((term, repr))
  986. else:
  987. _order.append((term, repr))
  988. ordered = sorted(_terms, key=key, reverse=True) \
  989. + sorted(_order, key=key, reverse=True)
  990. if data:
  991. return ordered, gens
  992. else:
  993. return [term for term, _ in ordered]
  994. def as_terms(self):
  995. """Transform an expression to a list of terms. """
  996. from .exprtools import decompose_power
  997. gens, terms = set(), []
  998. for term in Add.make_args(self):
  999. coeff, _term = term.as_coeff_Mul()
  1000. coeff = complex(coeff)
  1001. cpart, ncpart = {}, []
  1002. if _term is not S.One:
  1003. for factor in Mul.make_args(_term):
  1004. if factor.is_number:
  1005. try:
  1006. coeff *= complex(factor)
  1007. except (TypeError, ValueError):
  1008. pass
  1009. else:
  1010. continue
  1011. if factor.is_commutative:
  1012. base, exp = decompose_power(factor)
  1013. cpart[base] = exp
  1014. gens.add(base)
  1015. else:
  1016. ncpart.append(factor)
  1017. coeff = coeff.real, coeff.imag
  1018. ncpart = tuple(ncpart)
  1019. terms.append((term, (coeff, cpart, ncpart)))
  1020. gens = sorted(gens, key=default_sort_key)
  1021. k, indices = len(gens), {}
  1022. for i, g in enumerate(gens):
  1023. indices[g] = i
  1024. result = []
  1025. for term, (coeff, cpart, ncpart) in terms:
  1026. monom = [0]*k
  1027. for base, exp in cpart.items():
  1028. monom[indices[base]] = exp
  1029. result.append((term, (coeff, tuple(monom), ncpart)))
  1030. return result, gens
  1031. def removeO(self):
  1032. """Removes the additive O(..) symbol if there is one"""
  1033. return self
  1034. def getO(self):
  1035. """Returns the additive O(..) symbol if there is one, else None."""
  1036. return None
  1037. def getn(self):
  1038. """
  1039. Returns the order of the expression.
  1040. Explanation
  1041. ===========
  1042. The order is determined either from the O(...) term. If there
  1043. is no O(...) term, it returns None.
  1044. Examples
  1045. ========
  1046. >>> from sympy import O
  1047. >>> from sympy.abc import x
  1048. >>> (1 + x + O(x**2)).getn()
  1049. 2
  1050. >>> (1 + x).getn()
  1051. """
  1052. o = self.getO()
  1053. if o is None:
  1054. return None
  1055. elif o.is_Order:
  1056. o = o.expr
  1057. if o is S.One:
  1058. return S.Zero
  1059. if o.is_Symbol:
  1060. return S.One
  1061. if o.is_Pow:
  1062. return o.args[1]
  1063. if o.is_Mul: # x**n*log(x)**n or x**n/log(x)**n
  1064. for oi in o.args:
  1065. if oi.is_Symbol:
  1066. return S.One
  1067. if oi.is_Pow:
  1068. from .symbol import Dummy, Symbol
  1069. syms = oi.atoms(Symbol)
  1070. if len(syms) == 1:
  1071. x = syms.pop()
  1072. oi = oi.subs(x, Dummy('x', positive=True))
  1073. if oi.base.is_Symbol and oi.exp.is_Rational:
  1074. return abs(oi.exp)
  1075. raise NotImplementedError('not sure of order of %s' % o)
  1076. def count_ops(self, visual=None):
  1077. """wrapper for count_ops that returns the operation count."""
  1078. from .function import count_ops
  1079. return count_ops(self, visual)
  1080. def args_cnc(self, cset=False, warn=True, split_1=True):
  1081. """Return [commutative factors, non-commutative factors] of self.
  1082. Explanation
  1083. ===========
  1084. self is treated as a Mul and the ordering of the factors is maintained.
  1085. If ``cset`` is True the commutative factors will be returned in a set.
  1086. If there were repeated factors (as may happen with an unevaluated Mul)
  1087. then an error will be raised unless it is explicitly suppressed by
  1088. setting ``warn`` to False.
  1089. Note: -1 is always separated from a Number unless split_1 is False.
  1090. Examples
  1091. ========
  1092. >>> from sympy import symbols, oo
  1093. >>> A, B = symbols('A B', commutative=0)
  1094. >>> x, y = symbols('x y')
  1095. >>> (-2*x*y).args_cnc()
  1096. [[-1, 2, x, y], []]
  1097. >>> (-2.5*x).args_cnc()
  1098. [[-1, 2.5, x], []]
  1099. >>> (-2*x*A*B*y).args_cnc()
  1100. [[-1, 2, x, y], [A, B]]
  1101. >>> (-2*x*A*B*y).args_cnc(split_1=False)
  1102. [[-2, x, y], [A, B]]
  1103. >>> (-2*x*y).args_cnc(cset=True)
  1104. [{-1, 2, x, y}, []]
  1105. The arg is always treated as a Mul:
  1106. >>> (-2 + x + A).args_cnc()
  1107. [[], [x - 2 + A]]
  1108. >>> (-oo).args_cnc() # -oo is a singleton
  1109. [[-1, oo], []]
  1110. """
  1111. if self.is_Mul:
  1112. args = list(self.args)
  1113. else:
  1114. args = [self]
  1115. for i, mi in enumerate(args):
  1116. if not mi.is_commutative:
  1117. c = args[:i]
  1118. nc = args[i:]
  1119. break
  1120. else:
  1121. c = args
  1122. nc = []
  1123. if c and split_1 and (
  1124. c[0].is_Number and
  1125. c[0].is_extended_negative and
  1126. c[0] is not S.NegativeOne):
  1127. c[:1] = [S.NegativeOne, -c[0]]
  1128. if cset:
  1129. clen = len(c)
  1130. c = set(c)
  1131. if clen and warn and len(c) != clen:
  1132. raise ValueError('repeated commutative arguments: %s' %
  1133. [ci for ci in c if list(self.args).count(ci) > 1])
  1134. return [c, nc]
  1135. def coeff(self, x, n=1, right=False, _first=True):
  1136. """
  1137. Returns the coefficient from the term(s) containing ``x**n``. If ``n``
  1138. is zero then all terms independent of ``x`` will be returned.
  1139. Explanation
  1140. ===========
  1141. When ``x`` is noncommutative, the coefficient to the left (default) or
  1142. right of ``x`` can be returned. The keyword 'right' is ignored when
  1143. ``x`` is commutative.
  1144. Examples
  1145. ========
  1146. >>> from sympy import symbols
  1147. >>> from sympy.abc import x, y, z
  1148. You can select terms that have an explicit negative in front of them:
  1149. >>> (-x + 2*y).coeff(-1)
  1150. x
  1151. >>> (x - 2*y).coeff(-1)
  1152. 2*y
  1153. You can select terms with no Rational coefficient:
  1154. >>> (x + 2*y).coeff(1)
  1155. x
  1156. >>> (3 + 2*x + 4*x**2).coeff(1)
  1157. 0
  1158. You can select terms independent of x by making n=0; in this case
  1159. expr.as_independent(x)[0] is returned (and 0 will be returned instead
  1160. of None):
  1161. >>> (3 + 2*x + 4*x**2).coeff(x, 0)
  1162. 3
  1163. >>> eq = ((x + 1)**3).expand() + 1
  1164. >>> eq
  1165. x**3 + 3*x**2 + 3*x + 2
  1166. >>> [eq.coeff(x, i) for i in reversed(range(4))]
  1167. [1, 3, 3, 2]
  1168. >>> eq -= 2
  1169. >>> [eq.coeff(x, i) for i in reversed(range(4))]
  1170. [1, 3, 3, 0]
  1171. You can select terms that have a numerical term in front of them:
  1172. >>> (-x - 2*y).coeff(2)
  1173. -y
  1174. >>> from sympy import sqrt
  1175. >>> (x + sqrt(2)*x).coeff(sqrt(2))
  1176. x
  1177. The matching is exact:
  1178. >>> (3 + 2*x + 4*x**2).coeff(x)
  1179. 2
  1180. >>> (3 + 2*x + 4*x**2).coeff(x**2)
  1181. 4
  1182. >>> (3 + 2*x + 4*x**2).coeff(x**3)
  1183. 0
  1184. >>> (z*(x + y)**2).coeff((x + y)**2)
  1185. z
  1186. >>> (z*(x + y)**2).coeff(x + y)
  1187. 0
  1188. In addition, no factoring is done, so 1 + z*(1 + y) is not obtained
  1189. from the following:
  1190. >>> (x + z*(x + x*y)).coeff(x)
  1191. 1
  1192. If such factoring is desired, factor_terms can be used first:
  1193. >>> from sympy import factor_terms
  1194. >>> factor_terms(x + z*(x + x*y)).coeff(x)
  1195. z*(y + 1) + 1
  1196. >>> n, m, o = symbols('n m o', commutative=False)
  1197. >>> n.coeff(n)
  1198. 1
  1199. >>> (3*n).coeff(n)
  1200. 3
  1201. >>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
  1202. 1 + m
  1203. >>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
  1204. m
  1205. If there is more than one possible coefficient 0 is returned:
  1206. >>> (n*m + m*n).coeff(n)
  1207. 0
  1208. If there is only one possible coefficient, it is returned:
  1209. >>> (n*m + x*m*n).coeff(m*n)
  1210. x
  1211. >>> (n*m + x*m*n).coeff(m*n, right=1)
  1212. 1
  1213. See Also
  1214. ========
  1215. as_coefficient: separate the expression into a coefficient and factor
  1216. as_coeff_Add: separate the additive constant from an expression
  1217. as_coeff_Mul: separate the multiplicative constant from an expression
  1218. as_independent: separate x-dependent terms/factors from others
  1219. sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
  1220. sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
  1221. """
  1222. x = sympify(x)
  1223. if not isinstance(x, Basic):
  1224. return S.Zero
  1225. n = as_int(n)
  1226. if not x:
  1227. return S.Zero
  1228. if x == self:
  1229. if n == 1:
  1230. return S.One
  1231. return S.Zero
  1232. if x is S.One:
  1233. co = [a for a in Add.make_args(self)
  1234. if a.as_coeff_Mul()[0] is S.One]
  1235. if not co:
  1236. return S.Zero
  1237. return Add(*co)
  1238. if n == 0:
  1239. if x.is_Add and self.is_Add:
  1240. c = self.coeff(x, right=right)
  1241. if not c:
  1242. return S.Zero
  1243. if not right:
  1244. return self - Add(*[a*x for a in Add.make_args(c)])
  1245. return self - Add(*[x*a for a in Add.make_args(c)])
  1246. return self.as_independent(x, as_Add=True)[0]
  1247. # continue with the full method, looking for this power of x:
  1248. x = x**n
  1249. def incommon(l1, l2):
  1250. if not l1 or not l2:
  1251. return []
  1252. n = min(len(l1), len(l2))
  1253. for i in range(n):
  1254. if l1[i] != l2[i]:
  1255. return l1[:i]
  1256. return l1[:]
  1257. def find(l, sub, first=True):
  1258. """ Find where list sub appears in list l. When ``first`` is True
  1259. the first occurrence from the left is returned, else the last
  1260. occurrence is returned. Return None if sub is not in l.
  1261. Examples
  1262. ========
  1263. >> l = range(5)*2
  1264. >> find(l, [2, 3])
  1265. 2
  1266. >> find(l, [2, 3], first=0)
  1267. 7
  1268. >> find(l, [2, 4])
  1269. None
  1270. """
  1271. if not sub or not l or len(sub) > len(l):
  1272. return None
  1273. n = len(sub)
  1274. if not first:
  1275. l.reverse()
  1276. sub.reverse()
  1277. for i in range(0, len(l) - n + 1):
  1278. if all(l[i + j] == sub[j] for j in range(n)):
  1279. break
  1280. else:
  1281. i = None
  1282. if not first:
  1283. l.reverse()
  1284. sub.reverse()
  1285. if i is not None and not first:
  1286. i = len(l) - (i + n)
  1287. return i
  1288. co = []
  1289. args = Add.make_args(self)
  1290. self_c = self.is_commutative
  1291. x_c = x.is_commutative
  1292. if self_c and not x_c:
  1293. return S.Zero
  1294. if _first and self.is_Add and not self_c and not x_c:
  1295. # get the part that depends on x exactly
  1296. xargs = Mul.make_args(x)
  1297. d = Add(*[i for i in Add.make_args(self.as_independent(x)[1])
  1298. if all(xi in Mul.make_args(i) for xi in xargs)])
  1299. rv = d.coeff(x, right=right, _first=False)
  1300. if not rv.is_Add or not right:
  1301. return rv
  1302. c_part, nc_part = zip(*[i.args_cnc() for i in rv.args])
  1303. if has_variety(c_part):
  1304. return rv
  1305. return Add(*[Mul._from_args(i) for i in nc_part])
  1306. one_c = self_c or x_c
  1307. xargs, nx = x.args_cnc(cset=True, warn=bool(not x_c))
  1308. # find the parts that pass the commutative terms
  1309. for a in args:
  1310. margs, nc = a.args_cnc(cset=True, warn=bool(not self_c))
  1311. if nc is None:
  1312. nc = []
  1313. if len(xargs) > len(margs):
  1314. continue
  1315. resid = margs.difference(xargs)
  1316. if len(resid) + len(xargs) == len(margs):
  1317. if one_c:
  1318. co.append(Mul(*(list(resid) + nc)))
  1319. else:
  1320. co.append((resid, nc))
  1321. if one_c:
  1322. if co == []:
  1323. return S.Zero
  1324. elif co:
  1325. return Add(*co)
  1326. else: # both nc
  1327. # now check the non-comm parts
  1328. if not co:
  1329. return S.Zero
  1330. if all(n == co[0][1] for r, n in co):
  1331. ii = find(co[0][1], nx, right)
  1332. if ii is not None:
  1333. if not right:
  1334. return Mul(Add(*[Mul(*r) for r, c in co]), Mul(*co[0][1][:ii]))
  1335. else:
  1336. return Mul(*co[0][1][ii + len(nx):])
  1337. beg = reduce(incommon, (n[1] for n in co))
  1338. if beg:
  1339. ii = find(beg, nx, right)
  1340. if ii is not None:
  1341. if not right:
  1342. gcdc = co[0][0]
  1343. for i in range(1, len(co)):
  1344. gcdc = gcdc.intersection(co[i][0])
  1345. if not gcdc:
  1346. break
  1347. return Mul(*(list(gcdc) + beg[:ii]))
  1348. else:
  1349. m = ii + len(nx)
  1350. return Add(*[Mul(*(list(r) + n[m:])) for r, n in co])
  1351. end = list(reversed(
  1352. reduce(incommon, (list(reversed(n[1])) for n in co))))
  1353. if end:
  1354. ii = find(end, nx, right)
  1355. if ii is not None:
  1356. if not right:
  1357. return Add(*[Mul(*(list(r) + n[:-len(end) + ii])) for r, n in co])
  1358. else:
  1359. return Mul(*end[ii + len(nx):])
  1360. # look for single match
  1361. hit = None
  1362. for i, (r, n) in enumerate(co):
  1363. ii = find(n, nx, right)
  1364. if ii is not None:
  1365. if not hit:
  1366. hit = ii, r, n
  1367. else:
  1368. break
  1369. else:
  1370. if hit:
  1371. ii, r, n = hit
  1372. if not right:
  1373. return Mul(*(list(r) + n[:ii]))
  1374. else:
  1375. return Mul(*n[ii + len(nx):])
  1376. return S.Zero
  1377. def as_expr(self, *gens):
  1378. """
  1379. Convert a polynomial to a SymPy expression.
  1380. Examples
  1381. ========
  1382. >>> from sympy import sin
  1383. >>> from sympy.abc import x, y
  1384. >>> f = (x**2 + x*y).as_poly(x, y)
  1385. >>> f.as_expr()
  1386. x**2 + x*y
  1387. >>> sin(x).as_expr()
  1388. sin(x)
  1389. """
  1390. return self
  1391. def as_coefficient(self, expr):
  1392. """
  1393. Extracts symbolic coefficient at the given expression. In
  1394. other words, this functions separates 'self' into the product
  1395. of 'expr' and 'expr'-free coefficient. If such separation
  1396. is not possible it will return None.
  1397. Examples
  1398. ========
  1399. >>> from sympy import E, pi, sin, I, Poly
  1400. >>> from sympy.abc import x
  1401. >>> E.as_coefficient(E)
  1402. 1
  1403. >>> (2*E).as_coefficient(E)
  1404. 2
  1405. >>> (2*sin(E)*E).as_coefficient(E)
  1406. Two terms have E in them so a sum is returned. (If one were
  1407. desiring the coefficient of the term exactly matching E then
  1408. the constant from the returned expression could be selected.
  1409. Or, for greater precision, a method of Poly can be used to
  1410. indicate the desired term from which the coefficient is
  1411. desired.)
  1412. >>> (2*E + x*E).as_coefficient(E)
  1413. x + 2
  1414. >>> _.args[0] # just want the exact match
  1415. 2
  1416. >>> p = Poly(2*E + x*E); p
  1417. Poly(x*E + 2*E, x, E, domain='ZZ')
  1418. >>> p.coeff_monomial(E)
  1419. 2
  1420. >>> p.nth(0, 1)
  1421. 2
  1422. Since the following cannot be written as a product containing
  1423. E as a factor, None is returned. (If the coefficient ``2*x`` is
  1424. desired then the ``coeff`` method should be used.)
  1425. >>> (2*E*x + x).as_coefficient(E)
  1426. >>> (2*E*x + x).coeff(E)
  1427. 2*x
  1428. >>> (E*(x + 1) + x).as_coefficient(E)
  1429. >>> (2*pi*I).as_coefficient(pi*I)
  1430. 2
  1431. >>> (2*I).as_coefficient(pi*I)
  1432. See Also
  1433. ========
  1434. coeff: return sum of terms have a given factor
  1435. as_coeff_Add: separate the additive constant from an expression
  1436. as_coeff_Mul: separate the multiplicative constant from an expression
  1437. as_independent: separate x-dependent terms/factors from others
  1438. sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
  1439. sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
  1440. """
  1441. r = self.extract_multiplicatively(expr)
  1442. if r and not r.has(expr):
  1443. return r
  1444. def as_independent(self, *deps, **hint):
  1445. """
  1446. A mostly naive separation of a Mul or Add into arguments that are not
  1447. are dependent on deps. To obtain as complete a separation of variables
  1448. as possible, use a separation method first, e.g.:
  1449. * separatevars() to change Mul, Add and Pow (including exp) into Mul
  1450. * .expand(mul=True) to change Add or Mul into Add
  1451. * .expand(log=True) to change log expr into an Add
  1452. The only non-naive thing that is done here is to respect noncommutative
  1453. ordering of variables and to always return (0, 0) for `self` of zero
  1454. regardless of hints.
  1455. For nonzero `self`, the returned tuple (i, d) has the
  1456. following interpretation:
  1457. * i will has no variable that appears in deps
  1458. * d will either have terms that contain variables that are in deps, or
  1459. be equal to 0 (when self is an Add) or 1 (when self is a Mul)
  1460. * if self is an Add then self = i + d
  1461. * if self is a Mul then self = i*d
  1462. * otherwise (self, S.One) or (S.One, self) is returned.
  1463. To force the expression to be treated as an Add, use the hint as_Add=True
  1464. Examples
  1465. ========
  1466. -- self is an Add
  1467. >>> from sympy import sin, cos, exp
  1468. >>> from sympy.abc import x, y, z
  1469. >>> (x + x*y).as_independent(x)
  1470. (0, x*y + x)
  1471. >>> (x + x*y).as_independent(y)
  1472. (x, x*y)
  1473. >>> (2*x*sin(x) + y + x + z).as_independent(x)
  1474. (y + z, 2*x*sin(x) + x)
  1475. >>> (2*x*sin(x) + y + x + z).as_independent(x, y)
  1476. (z, 2*x*sin(x) + x + y)
  1477. -- self is a Mul
  1478. >>> (x*sin(x)*cos(y)).as_independent(x)
  1479. (cos(y), x*sin(x))
  1480. non-commutative terms cannot always be separated out when self is a Mul
  1481. >>> from sympy import symbols
  1482. >>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
  1483. >>> (n1 + n1*n2).as_independent(n2)
  1484. (n1, n1*n2)
  1485. >>> (n2*n1 + n1*n2).as_independent(n2)
  1486. (0, n1*n2 + n2*n1)
  1487. >>> (n1*n2*n3).as_independent(n1)
  1488. (1, n1*n2*n3)
  1489. >>> (n1*n2*n3).as_independent(n2)
  1490. (n1, n2*n3)
  1491. >>> ((x-n1)*(x-y)).as_independent(x)
  1492. (1, (x - y)*(x - n1))
  1493. -- self is anything else:
  1494. >>> (sin(x)).as_independent(x)
  1495. (1, sin(x))
  1496. >>> (sin(x)).as_independent(y)
  1497. (sin(x), 1)
  1498. >>> exp(x+y).as_independent(x)
  1499. (1, exp(x + y))
  1500. -- force self to be treated as an Add:
  1501. >>> (3*x).as_independent(x, as_Add=True)
  1502. (0, 3*x)
  1503. -- force self to be treated as a Mul:
  1504. >>> (3+x).as_independent(x, as_Add=False)
  1505. (1, x + 3)
  1506. >>> (-3+x).as_independent(x, as_Add=False)
  1507. (1, x - 3)
  1508. Note how the below differs from the above in making the
  1509. constant on the dep term positive.
  1510. >>> (y*(-3+x)).as_independent(x)
  1511. (y, x - 3)
  1512. -- use .as_independent() for true independence testing instead
  1513. of .has(). The former considers only symbols in the free
  1514. symbols while the latter considers all symbols
  1515. >>> from sympy import Integral
  1516. >>> I = Integral(x, (x, 1, 2))
  1517. >>> I.has(x)
  1518. True
  1519. >>> x in I.free_symbols
  1520. False
  1521. >>> I.as_independent(x) == (I, 1)
  1522. True
  1523. >>> (I + x).as_independent(x) == (I, x)
  1524. True
  1525. Note: when trying to get independent terms, a separation method
  1526. might need to be used first. In this case, it is important to keep
  1527. track of what you send to this routine so you know how to interpret
  1528. the returned values
  1529. >>> from sympy import separatevars, log
  1530. >>> separatevars(exp(x+y)).as_independent(x)
  1531. (exp(y), exp(x))
  1532. >>> (x + x*y).as_independent(y)
  1533. (x, x*y)
  1534. >>> separatevars(x + x*y).as_independent(y)
  1535. (x, y + 1)
  1536. >>> (x*(1 + y)).as_independent(y)
  1537. (x, y + 1)
  1538. >>> (x*(1 + y)).expand(mul=True).as_independent(y)
  1539. (x, x*y)
  1540. >>> a, b=symbols('a b', positive=True)
  1541. >>> (log(a*b).expand(log=True)).as_independent(b)
  1542. (log(a), log(b))
  1543. See Also
  1544. ========
  1545. .separatevars(), .expand(log=True), sympy.core.add.Add.as_two_terms(),
  1546. sympy.core.mul.Mul.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
  1547. """
  1548. from .symbol import Symbol
  1549. from .add import _unevaluated_Add
  1550. from .mul import _unevaluated_Mul
  1551. if self.is_zero:
  1552. return S.Zero, S.Zero
  1553. func = self.func
  1554. if hint.get('as_Add', isinstance(self, Add) ):
  1555. want = Add
  1556. else:
  1557. want = Mul
  1558. # sift out deps into symbolic and other and ignore
  1559. # all symbols but those that are in the free symbols
  1560. sym = set()
  1561. other = []
  1562. for d in deps:
  1563. if isinstance(d, Symbol): # Symbol.is_Symbol is True
  1564. sym.add(d)
  1565. else:
  1566. other.append(d)
  1567. def has(e):
  1568. """return the standard has() if there are no literal symbols, else
  1569. check to see that symbol-deps are in the free symbols."""
  1570. has_other = e.has(*other)
  1571. if not sym:
  1572. return has_other
  1573. return has_other or e.has(*(e.free_symbols & sym))
  1574. if (want is not func or
  1575. func is not Add and func is not Mul):
  1576. if has(self):
  1577. return (want.identity, self)
  1578. else:
  1579. return (self, want.identity)
  1580. else:
  1581. if func is Add:
  1582. args = list(self.args)
  1583. else:
  1584. args, nc = self.args_cnc()
  1585. d = sift(args, has)
  1586. depend = d[True]
  1587. indep = d[False]
  1588. if func is Add: # all terms were treated as commutative
  1589. return (Add(*indep), _unevaluated_Add(*depend))
  1590. else: # handle noncommutative by stopping at first dependent term
  1591. for i, n in enumerate(nc):
  1592. if has(n):
  1593. depend.extend(nc[i:])
  1594. break
  1595. indep.append(n)
  1596. return Mul(*indep), (
  1597. Mul(*depend, evaluate=False) if nc else
  1598. _unevaluated_Mul(*depend))
  1599. def as_real_imag(self, deep=True, **hints):
  1600. """Performs complex expansion on 'self' and returns a tuple
  1601. containing collected both real and imaginary parts. This
  1602. method cannot be confused with re() and im() functions,
  1603. which does not perform complex expansion at evaluation.
  1604. However it is possible to expand both re() and im()
  1605. functions and get exactly the same results as with
  1606. a single call to this function.
  1607. >>> from sympy import symbols, I
  1608. >>> x, y = symbols('x,y', real=True)
  1609. >>> (x + y*I).as_real_imag()
  1610. (x, y)
  1611. >>> from sympy.abc import z, w
  1612. >>> (z + w*I).as_real_imag()
  1613. (re(z) - im(w), re(w) + im(z))
  1614. """
  1615. if hints.get('ignore') == self:
  1616. return None
  1617. else:
  1618. from sympy.functions.elementary.complexes import im, re
  1619. return (re(self), im(self))
  1620. def as_powers_dict(self):
  1621. """Return self as a dictionary of factors with each factor being
  1622. treated as a power. The keys are the bases of the factors and the
  1623. values, the corresponding exponents. The resulting dictionary should
  1624. be used with caution if the expression is a Mul and contains non-
  1625. commutative factors since the order that they appeared will be lost in
  1626. the dictionary.
  1627. See Also
  1628. ========
  1629. as_ordered_factors: An alternative for noncommutative applications,
  1630. returning an ordered list of factors.
  1631. args_cnc: Similar to as_ordered_factors, but guarantees separation
  1632. of commutative and noncommutative factors.
  1633. """
  1634. d = defaultdict(int)
  1635. d.update(dict([self.as_base_exp()]))
  1636. return d
  1637. def as_coefficients_dict(self):
  1638. """Return a dictionary mapping terms to their Rational coefficient.
  1639. Since the dictionary is a defaultdict, inquiries about terms which
  1640. were not present will return a coefficient of 0. If an expression is
  1641. not an Add it is considered to have a single term.
  1642. Examples
  1643. ========
  1644. >>> from sympy.abc import a, x
  1645. >>> (3*x + a*x + 4).as_coefficients_dict()
  1646. {1: 4, x: 3, a*x: 1}
  1647. >>> _[a]
  1648. 0
  1649. >>> (3*a*x).as_coefficients_dict()
  1650. {a*x: 3}
  1651. """
  1652. c, m = self.as_coeff_Mul()
  1653. if not c.is_Rational:
  1654. c = S.One
  1655. m = self
  1656. d = defaultdict(int)
  1657. d.update({m: c})
  1658. return d
  1659. def as_base_exp(self):
  1660. # a -> b ** e
  1661. return self, S.One
  1662. def as_coeff_mul(self, *deps, **kwargs):
  1663. """Return the tuple (c, args) where self is written as a Mul, ``m``.
  1664. c should be a Rational multiplied by any factors of the Mul that are
  1665. independent of deps.
  1666. args should be a tuple of all other factors of m; args is empty
  1667. if self is a Number or if self is independent of deps (when given).
  1668. This should be used when you do not know if self is a Mul or not but
  1669. you want to treat self as a Mul or if you want to process the
  1670. individual arguments of the tail of self as a Mul.
  1671. - if you know self is a Mul and want only the head, use self.args[0];
  1672. - if you do not want to process the arguments of the tail but need the
  1673. tail then use self.as_two_terms() which gives the head and tail;
  1674. - if you want to split self into an independent and dependent parts
  1675. use ``self.as_independent(*deps)``
  1676. >>> from sympy import S
  1677. >>> from sympy.abc import x, y
  1678. >>> (S(3)).as_coeff_mul()
  1679. (3, ())
  1680. >>> (3*x*y).as_coeff_mul()
  1681. (3, (x, y))
  1682. >>> (3*x*y).as_coeff_mul(x)
  1683. (3*y, (x,))
  1684. >>> (3*y).as_coeff_mul(x)
  1685. (3*y, ())
  1686. """
  1687. if deps:
  1688. if not self.has(*deps):
  1689. return self, tuple()
  1690. return S.One, (self,)
  1691. def as_coeff_add(self, *deps):
  1692. """Return the tuple (c, args) where self is written as an Add, ``a``.
  1693. c should be a Rational added to any terms of the Add that are
  1694. independent of deps.
  1695. args should be a tuple of all other terms of ``a``; args is empty
  1696. if self is a Number or if self is independent of deps (when given).
  1697. This should be used when you do not know if self is an Add or not but
  1698. you want to treat self as an Add or if you want to process the
  1699. individual arguments of the tail of self as an Add.
  1700. - if you know self is an Add and want only the head, use self.args[0];
  1701. - if you do not want to process the arguments of the tail but need the
  1702. tail then use self.as_two_terms() which gives the head and tail.
  1703. - if you want to split self into an independent and dependent parts
  1704. use ``self.as_independent(*deps)``
  1705. >>> from sympy import S
  1706. >>> from sympy.abc import x, y
  1707. >>> (S(3)).as_coeff_add()
  1708. (3, ())
  1709. >>> (3 + x).as_coeff_add()
  1710. (3, (x,))
  1711. >>> (3 + x + y).as_coeff_add(x)
  1712. (y + 3, (x,))
  1713. >>> (3 + y).as_coeff_add(x)
  1714. (y + 3, ())
  1715. """
  1716. if deps:
  1717. if not self.has_free(*deps):
  1718. return self, tuple()
  1719. return S.Zero, (self,)
  1720. def primitive(self):
  1721. """Return the positive Rational that can be extracted non-recursively
  1722. from every term of self (i.e., self is treated like an Add). This is
  1723. like the as_coeff_Mul() method but primitive always extracts a positive
  1724. Rational (never a negative or a Float).
  1725. Examples
  1726. ========
  1727. >>> from sympy.abc import x
  1728. >>> (3*(x + 1)**2).primitive()
  1729. (3, (x + 1)**2)
  1730. >>> a = (6*x + 2); a.primitive()
  1731. (2, 3*x + 1)
  1732. >>> b = (x/2 + 3); b.primitive()
  1733. (1/2, x + 6)
  1734. >>> (a*b).primitive() == (1, a*b)
  1735. True
  1736. """
  1737. if not self:
  1738. return S.One, S.Zero
  1739. c, r = self.as_coeff_Mul(rational=True)
  1740. if c.is_negative:
  1741. c, r = -c, -r
  1742. return c, r
  1743. def as_content_primitive(self, radical=False, clear=True):
  1744. """This method should recursively remove a Rational from all arguments
  1745. and return that (content) and the new self (primitive). The content
  1746. should always be positive and ``Mul(*foo.as_content_primitive()) == foo``.
  1747. The primitive need not be in canonical form and should try to preserve
  1748. the underlying structure if possible (i.e. expand_mul should not be
  1749. applied to self).
  1750. Examples
  1751. ========
  1752. >>> from sympy import sqrt
  1753. >>> from sympy.abc import x, y, z
  1754. >>> eq = 2 + 2*x + 2*y*(3 + 3*y)
  1755. The as_content_primitive function is recursive and retains structure:
  1756. >>> eq.as_content_primitive()
  1757. (2, x + 3*y*(y + 1) + 1)
  1758. Integer powers will have Rationals extracted from the base:
  1759. >>> ((2 + 6*x)**2).as_content_primitive()
  1760. (4, (3*x + 1)**2)
  1761. >>> ((2 + 6*x)**(2*y)).as_content_primitive()
  1762. (1, (2*(3*x + 1))**(2*y))
  1763. Terms may end up joining once their as_content_primitives are added:
  1764. >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
  1765. (11, x*(y + 1))
  1766. >>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
  1767. (9, x*(y + 1))
  1768. >>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive()
  1769. (1, 6.0*x*(y + 1) + 3*z*(y + 1))
  1770. >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive()
  1771. (121, x**2*(y + 1)**2)
  1772. >>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive()
  1773. (1, 4.84*x**2*(y + 1)**2)
  1774. Radical content can also be factored out of the primitive:
  1775. >>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
  1776. (2, sqrt(2)*(1 + 2*sqrt(5)))
  1777. If clear=False (default is True) then content will not be removed
  1778. from an Add if it can be distributed to leave one or more
  1779. terms with integer coefficients.
  1780. >>> (x/2 + y).as_content_primitive()
  1781. (1/2, x + 2*y)
  1782. >>> (x/2 + y).as_content_primitive(clear=False)
  1783. (1, x/2 + y)
  1784. """
  1785. return S.One, self
  1786. def as_numer_denom(self):
  1787. """ expression -> a/b -> a, b
  1788. This is just a stub that should be defined by
  1789. an object's class methods to get anything else.
  1790. See Also
  1791. ========
  1792. normal: return ``a/b`` instead of ``(a, b)``
  1793. """
  1794. return self, S.One
  1795. def normal(self):
  1796. """ expression -> a/b
  1797. See Also
  1798. ========
  1799. as_numer_denom: return ``(a, b)`` instead of ``a/b``
  1800. """
  1801. from .mul import _unevaluated_Mul
  1802. n, d = self.as_numer_denom()
  1803. if d is S.One:
  1804. return n
  1805. if d.is_Number:
  1806. return _unevaluated_Mul(n, 1/d)
  1807. else:
  1808. return n/d
  1809. def extract_multiplicatively(self, c):
  1810. """Return None if it's not possible to make self in the form
  1811. c * something in a nice way, i.e. preserving the properties
  1812. of arguments of self.
  1813. Examples
  1814. ========
  1815. >>> from sympy import symbols, Rational
  1816. >>> x, y = symbols('x,y', real=True)
  1817. >>> ((x*y)**3).extract_multiplicatively(x**2 * y)
  1818. x*y**2
  1819. >>> ((x*y)**3).extract_multiplicatively(x**4 * y)
  1820. >>> (2*x).extract_multiplicatively(2)
  1821. x
  1822. >>> (2*x).extract_multiplicatively(3)
  1823. >>> (Rational(1, 2)*x).extract_multiplicatively(3)
  1824. x/6
  1825. """
  1826. from sympy.functions.elementary.exponential import exp
  1827. from .add import _unevaluated_Add
  1828. c = sympify(c)
  1829. if self is S.NaN:
  1830. return None
  1831. if c is S.One:
  1832. return self
  1833. elif c == self:
  1834. return S.One
  1835. if c.is_Add:
  1836. cc, pc = c.primitive()
  1837. if cc is not S.One:
  1838. c = Mul(cc, pc, evaluate=False)
  1839. if c.is_Mul:
  1840. a, b = c.as_two_terms()
  1841. x = self.extract_multiplicatively(a)
  1842. if x is not None:
  1843. return x.extract_multiplicatively(b)
  1844. else:
  1845. return x
  1846. quotient = self / c
  1847. if self.is_Number:
  1848. if self is S.Infinity:
  1849. if c.is_positive:
  1850. return S.Infinity
  1851. elif self is S.NegativeInfinity:
  1852. if c.is_negative:
  1853. return S.Infinity
  1854. elif c.is_positive:
  1855. return S.NegativeInfinity
  1856. elif self is S.ComplexInfinity:
  1857. if not c.is_zero:
  1858. return S.ComplexInfinity
  1859. elif self.is_Integer:
  1860. if not quotient.is_Integer:
  1861. return None
  1862. elif self.is_positive and quotient.is_negative:
  1863. return None
  1864. else:
  1865. return quotient
  1866. elif self.is_Rational:
  1867. if not quotient.is_Rational:
  1868. return None
  1869. elif self.is_positive and quotient.is_negative:
  1870. return None
  1871. else:
  1872. return quotient
  1873. elif self.is_Float:
  1874. if not quotient.is_Float:
  1875. return None
  1876. elif self.is_positive and quotient.is_negative:
  1877. return None
  1878. else:
  1879. return quotient
  1880. elif self.is_NumberSymbol or self.is_Symbol or self is S.ImaginaryUnit:
  1881. if quotient.is_Mul and len(quotient.args) == 2:
  1882. if quotient.args[0].is_Integer and quotient.args[0].is_positive and quotient.args[1] == self:
  1883. return quotient
  1884. elif quotient.is_Integer and c.is_Number:
  1885. return quotient
  1886. elif self.is_Add:
  1887. cs, ps = self.primitive()
  1888. # assert cs >= 1
  1889. if c.is_Number and c is not S.NegativeOne:
  1890. # assert c != 1 (handled at top)
  1891. if cs is not S.One:
  1892. if c.is_negative:
  1893. xc = -(cs.extract_multiplicatively(-c))
  1894. else:
  1895. xc = cs.extract_multiplicatively(c)
  1896. if xc is not None:
  1897. return xc*ps # rely on 2-arg Mul to restore Add
  1898. return # |c| != 1 can only be extracted from cs
  1899. if c == ps:
  1900. return cs
  1901. # check args of ps
  1902. newargs = []
  1903. for arg in ps.args:
  1904. newarg = arg.extract_multiplicatively(c)
  1905. if newarg is None:
  1906. return # all or nothing
  1907. newargs.append(newarg)
  1908. if cs is not S.One:
  1909. args = [cs*t for t in newargs]
  1910. # args may be in different order
  1911. return _unevaluated_Add(*args)
  1912. else:
  1913. return Add._from_args(newargs)
  1914. elif self.is_Mul:
  1915. args = list(self.args)
  1916. for i, arg in enumerate(args):
  1917. newarg = arg.extract_multiplicatively(c)
  1918. if newarg is not None:
  1919. args[i] = newarg
  1920. return Mul(*args)
  1921. elif self.is_Pow or isinstance(self, exp):
  1922. sb, se = self.as_base_exp()
  1923. cb, ce = c.as_base_exp()
  1924. if cb == sb:
  1925. new_exp = se.extract_additively(ce)
  1926. if new_exp is not None:
  1927. return Pow(sb, new_exp)
  1928. elif c == sb:
  1929. new_exp = self.exp.extract_additively(1)
  1930. if new_exp is not None:
  1931. return Pow(sb, new_exp)
  1932. def extract_additively(self, c):
  1933. """Return self - c if it's possible to subtract c from self and
  1934. make all matching coefficients move towards zero, else return None.
  1935. Examples
  1936. ========
  1937. >>> from sympy.abc import x, y
  1938. >>> e = 2*x + 3
  1939. >>> e.extract_additively(x + 1)
  1940. x + 2
  1941. >>> e.extract_additively(3*x)
  1942. >>> e.extract_additively(4)
  1943. >>> (y*(x + 1)).extract_additively(x + 1)
  1944. >>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1)
  1945. (x + 1)*(x + 2*y) + 3
  1946. See Also
  1947. ========
  1948. extract_multiplicatively
  1949. coeff
  1950. as_coefficient
  1951. """
  1952. c = sympify(c)
  1953. if self is S.NaN:
  1954. return None
  1955. if c.is_zero:
  1956. return self
  1957. elif c == self:
  1958. return S.Zero
  1959. elif self == S.Zero:
  1960. return None
  1961. if self.is_Number:
  1962. if not c.is_Number:
  1963. return None
  1964. co = self
  1965. diff = co - c
  1966. # XXX should we match types? i.e should 3 - .1 succeed?
  1967. if (co > 0 and diff > 0 and diff < co or
  1968. co < 0 and diff < 0 and diff > co):
  1969. return diff
  1970. return None
  1971. if c.is_Number:
  1972. co, t = self.as_coeff_Add()
  1973. xa = co.extract_additively(c)
  1974. if xa is None:
  1975. return None
  1976. return xa + t
  1977. # handle the args[0].is_Number case separately
  1978. # since we will have trouble looking for the coeff of
  1979. # a number.
  1980. if c.is_Add and c.args[0].is_Number:
  1981. # whole term as a term factor
  1982. co = self.coeff(c)
  1983. xa0 = (co.extract_additively(1) or 0)*c
  1984. if xa0:
  1985. diff = self - co*c
  1986. return (xa0 + (diff.extract_additively(c) or diff)) or None
  1987. # term-wise
  1988. h, t = c.as_coeff_Add()
  1989. sh, st = self.as_coeff_Add()
  1990. xa = sh.extract_additively(h)
  1991. if xa is None:
  1992. return None
  1993. xa2 = st.extract_additively(t)
  1994. if xa2 is None:
  1995. return None
  1996. return xa + xa2
  1997. # whole term as a term factor
  1998. co, diff = _corem(self, c)
  1999. xa0 = (co.extract_additively(1) or 0)*c
  2000. if xa0:
  2001. return (xa0 + (diff.extract_additively(c) or diff)) or None
  2002. # term-wise
  2003. coeffs = []
  2004. for a in Add.make_args(c):
  2005. ac, at = a.as_coeff_Mul()
  2006. co = self.coeff(at)
  2007. if not co:
  2008. return None
  2009. coc, cot = co.as_coeff_Add()
  2010. xa = coc.extract_additively(ac)
  2011. if xa is None:
  2012. return None
  2013. self -= co*at
  2014. coeffs.append((cot + xa)*at)
  2015. coeffs.append(self)
  2016. return Add(*coeffs)
  2017. @property
  2018. def expr_free_symbols(self):
  2019. """
  2020. Like ``free_symbols``, but returns the free symbols only if
  2021. they are contained in an expression node.
  2022. Examples
  2023. ========
  2024. >>> from sympy.abc import x, y
  2025. >>> (x + y).expr_free_symbols # doctest: +SKIP
  2026. {x, y}
  2027. If the expression is contained in a non-expression object, do not return
  2028. the free symbols. Compare:
  2029. >>> from sympy import Tuple
  2030. >>> t = Tuple(x + y)
  2031. >>> t.expr_free_symbols # doctest: +SKIP
  2032. set()
  2033. >>> t.free_symbols
  2034. {x, y}
  2035. """
  2036. sympy_deprecation_warning("""
  2037. The expr_free_symbols property is deprecated. Use free_symbols to get
  2038. the free symbols of an expression.
  2039. """,
  2040. deprecated_since_version="1.9",
  2041. active_deprecations_target="deprecated-expr-free-symbols")
  2042. return {j for i in self.args for j in i.expr_free_symbols}
  2043. def could_extract_minus_sign(self):
  2044. """Return True if self has -1 as a leading factor or has
  2045. more literal negative signs than positive signs in a sum,
  2046. otherwise False.
  2047. Examples
  2048. ========
  2049. >>> from sympy.abc import x, y
  2050. >>> e = x - y
  2051. >>> {i.could_extract_minus_sign() for i in (e, -e)}
  2052. {False, True}
  2053. Though the ``y - x`` is considered like ``-(x - y)``, since it
  2054. is in a product without a leading factor of -1, the result is
  2055. false below:
  2056. >>> (x*(y - x)).could_extract_minus_sign()
  2057. False
  2058. To put something in canonical form wrt to sign, use `signsimp`:
  2059. >>> from sympy import signsimp
  2060. >>> signsimp(x*(y - x))
  2061. -x*(x - y)
  2062. >>> _.could_extract_minus_sign()
  2063. True
  2064. """
  2065. return False
  2066. def extract_branch_factor(self, allow_half=False):
  2067. """
  2068. Try to write self as ``exp_polar(2*pi*I*n)*z`` in a nice way.
  2069. Return (z, n).
  2070. >>> from sympy import exp_polar, I, pi
  2071. >>> from sympy.abc import x, y
  2072. >>> exp_polar(I*pi).extract_branch_factor()
  2073. (exp_polar(I*pi), 0)
  2074. >>> exp_polar(2*I*pi).extract_branch_factor()
  2075. (1, 1)
  2076. >>> exp_polar(-pi*I).extract_branch_factor()
  2077. (exp_polar(I*pi), -1)
  2078. >>> exp_polar(3*pi*I + x).extract_branch_factor()
  2079. (exp_polar(x + I*pi), 1)
  2080. >>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor()
  2081. (y*exp_polar(2*pi*x), -1)
  2082. >>> exp_polar(-I*pi/2).extract_branch_factor()
  2083. (exp_polar(-I*pi/2), 0)
  2084. If allow_half is True, also extract exp_polar(I*pi):
  2085. >>> exp_polar(I*pi).extract_branch_factor(allow_half=True)
  2086. (1, 1/2)
  2087. >>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True)
  2088. (1, 1)
  2089. >>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True)
  2090. (1, 3/2)
  2091. >>> exp_polar(-I*pi).extract_branch_factor(allow_half=True)
  2092. (1, -1/2)
  2093. """
  2094. from sympy.functions.elementary.exponential import exp_polar
  2095. from sympy.functions.elementary.integers import ceiling
  2096. n = S.Zero
  2097. res = S.One
  2098. args = Mul.make_args(self)
  2099. exps = []
  2100. for arg in args:
  2101. if isinstance(arg, exp_polar):
  2102. exps += [arg.exp]
  2103. else:
  2104. res *= arg
  2105. piimult = S.Zero
  2106. extras = []
  2107. ipi = S.Pi*S.ImaginaryUnit
  2108. while exps:
  2109. exp = exps.pop()
  2110. if exp.is_Add:
  2111. exps += exp.args
  2112. continue
  2113. if exp.is_Mul:
  2114. coeff = exp.as_coefficient(ipi)
  2115. if coeff is not None:
  2116. piimult += coeff
  2117. continue
  2118. extras += [exp]
  2119. if piimult.is_number:
  2120. coeff = piimult
  2121. tail = ()
  2122. else:
  2123. coeff, tail = piimult.as_coeff_add(*piimult.free_symbols)
  2124. # round down to nearest multiple of 2
  2125. branchfact = ceiling(coeff/2 - S.Half)*2
  2126. n += branchfact/2
  2127. c = coeff - branchfact
  2128. if allow_half:
  2129. nc = c.extract_additively(1)
  2130. if nc is not None:
  2131. n += S.Half
  2132. c = nc
  2133. newexp = ipi*Add(*((c, ) + tail)) + Add(*extras)
  2134. if newexp != 0:
  2135. res *= exp_polar(newexp)
  2136. return res, n
  2137. def is_polynomial(self, *syms):
  2138. r"""
  2139. Return True if self is a polynomial in syms and False otherwise.
  2140. This checks if self is an exact polynomial in syms. This function
  2141. returns False for expressions that are "polynomials" with symbolic
  2142. exponents. Thus, you should be able to apply polynomial algorithms to
  2143. expressions for which this returns True, and Poly(expr, \*syms) should
  2144. work if and only if expr.is_polynomial(\*syms) returns True. The
  2145. polynomial does not have to be in expanded form. If no symbols are
  2146. given, all free symbols in the expression will be used.
  2147. This is not part of the assumptions system. You cannot do
  2148. Symbol('z', polynomial=True).
  2149. Examples
  2150. ========
  2151. >>> from sympy import Symbol, Function
  2152. >>> x = Symbol('x')
  2153. >>> ((x**2 + 1)**4).is_polynomial(x)
  2154. True
  2155. >>> ((x**2 + 1)**4).is_polynomial()
  2156. True
  2157. >>> (2**x + 1).is_polynomial(x)
  2158. False
  2159. >>> (2**x + 1).is_polynomial(2**x)
  2160. True
  2161. >>> f = Function('f')
  2162. >>> (f(x) + 1).is_polynomial(x)
  2163. False
  2164. >>> (f(x) + 1).is_polynomial(f(x))
  2165. True
  2166. >>> (1/f(x) + 1).is_polynomial(f(x))
  2167. False
  2168. >>> n = Symbol('n', nonnegative=True, integer=True)
  2169. >>> (x**n + 1).is_polynomial(x)
  2170. False
  2171. This function does not attempt any nontrivial simplifications that may
  2172. result in an expression that does not appear to be a polynomial to
  2173. become one.
  2174. >>> from sympy import sqrt, factor, cancel
  2175. >>> y = Symbol('y', positive=True)
  2176. >>> a = sqrt(y**2 + 2*y + 1)
  2177. >>> a.is_polynomial(y)
  2178. False
  2179. >>> factor(a)
  2180. y + 1
  2181. >>> factor(a).is_polynomial(y)
  2182. True
  2183. >>> b = (y**2 + 2*y + 1)/(y + 1)
  2184. >>> b.is_polynomial(y)
  2185. False
  2186. >>> cancel(b)
  2187. y + 1
  2188. >>> cancel(b).is_polynomial(y)
  2189. True
  2190. See also .is_rational_function()
  2191. """
  2192. if syms:
  2193. syms = set(map(sympify, syms))
  2194. else:
  2195. syms = self.free_symbols
  2196. if not syms:
  2197. return True
  2198. return self._eval_is_polynomial(syms)
  2199. def _eval_is_polynomial(self, syms):
  2200. if self in syms:
  2201. return True
  2202. if not self.has_free(*syms):
  2203. # constant polynomial
  2204. return True
  2205. # subclasses should return True or False
  2206. def is_rational_function(self, *syms):
  2207. """
  2208. Test whether function is a ratio of two polynomials in the given
  2209. symbols, syms. When syms is not given, all free symbols will be used.
  2210. The rational function does not have to be in expanded or in any kind of
  2211. canonical form.
  2212. This function returns False for expressions that are "rational
  2213. functions" with symbolic exponents. Thus, you should be able to call
  2214. .as_numer_denom() and apply polynomial algorithms to the result for
  2215. expressions for which this returns True.
  2216. This is not part of the assumptions system. You cannot do
  2217. Symbol('z', rational_function=True).
  2218. Examples
  2219. ========
  2220. >>> from sympy import Symbol, sin
  2221. >>> from sympy.abc import x, y
  2222. >>> (x/y).is_rational_function()
  2223. True
  2224. >>> (x**2).is_rational_function()
  2225. True
  2226. >>> (x/sin(y)).is_rational_function(y)
  2227. False
  2228. >>> n = Symbol('n', integer=True)
  2229. >>> (x**n + 1).is_rational_function(x)
  2230. False
  2231. This function does not attempt any nontrivial simplifications that may
  2232. result in an expression that does not appear to be a rational function
  2233. to become one.
  2234. >>> from sympy import sqrt, factor
  2235. >>> y = Symbol('y', positive=True)
  2236. >>> a = sqrt(y**2 + 2*y + 1)/y
  2237. >>> a.is_rational_function(y)
  2238. False
  2239. >>> factor(a)
  2240. (y + 1)/y
  2241. >>> factor(a).is_rational_function(y)
  2242. True
  2243. See also is_algebraic_expr().
  2244. """
  2245. if self in [S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
  2246. return False
  2247. if syms:
  2248. syms = set(map(sympify, syms))
  2249. else:
  2250. syms = self.free_symbols
  2251. if not syms:
  2252. return True
  2253. return self._eval_is_rational_function(syms)
  2254. def _eval_is_rational_function(self, syms):
  2255. if self in syms:
  2256. return True
  2257. if not self.has_free(*syms):
  2258. return True
  2259. # subclasses should return True or False
  2260. def is_meromorphic(self, x, a):
  2261. """
  2262. This tests whether an expression is meromorphic as
  2263. a function of the given symbol ``x`` at the point ``a``.
  2264. This method is intended as a quick test that will return
  2265. None if no decision can be made without simplification or
  2266. more detailed analysis.
  2267. Examples
  2268. ========
  2269. >>> from sympy import zoo, log, sin, sqrt
  2270. >>> from sympy.abc import x
  2271. >>> f = 1/x**2 + 1 - 2*x**3
  2272. >>> f.is_meromorphic(x, 0)
  2273. True
  2274. >>> f.is_meromorphic(x, 1)
  2275. True
  2276. >>> f.is_meromorphic(x, zoo)
  2277. True
  2278. >>> g = x**log(3)
  2279. >>> g.is_meromorphic(x, 0)
  2280. False
  2281. >>> g.is_meromorphic(x, 1)
  2282. True
  2283. >>> g.is_meromorphic(x, zoo)
  2284. False
  2285. >>> h = sin(1/x)*x**2
  2286. >>> h.is_meromorphic(x, 0)
  2287. False
  2288. >>> h.is_meromorphic(x, 1)
  2289. True
  2290. >>> h.is_meromorphic(x, zoo)
  2291. True
  2292. Multivalued functions are considered meromorphic when their
  2293. branches are meromorphic. Thus most functions are meromorphic
  2294. everywhere except at essential singularities and branch points.
  2295. In particular, they will be meromorphic also on branch cuts
  2296. except at their endpoints.
  2297. >>> log(x).is_meromorphic(x, -1)
  2298. True
  2299. >>> log(x).is_meromorphic(x, 0)
  2300. False
  2301. >>> sqrt(x).is_meromorphic(x, -1)
  2302. True
  2303. >>> sqrt(x).is_meromorphic(x, 0)
  2304. False
  2305. """
  2306. if not x.is_symbol:
  2307. raise TypeError("{} should be of symbol type".format(x))
  2308. a = sympify(a)
  2309. return self._eval_is_meromorphic(x, a)
  2310. def _eval_is_meromorphic(self, x, a):
  2311. if self == x:
  2312. return True
  2313. if not self.has_free(x):
  2314. return True
  2315. # subclasses should return True or False
  2316. def is_algebraic_expr(self, *syms):
  2317. """
  2318. This tests whether a given expression is algebraic or not, in the
  2319. given symbols, syms. When syms is not given, all free symbols
  2320. will be used. The rational function does not have to be in expanded
  2321. or in any kind of canonical form.
  2322. This function returns False for expressions that are "algebraic
  2323. expressions" with symbolic exponents. This is a simple extension to the
  2324. is_rational_function, including rational exponentiation.
  2325. Examples
  2326. ========
  2327. >>> from sympy import Symbol, sqrt
  2328. >>> x = Symbol('x', real=True)
  2329. >>> sqrt(1 + x).is_rational_function()
  2330. False
  2331. >>> sqrt(1 + x).is_algebraic_expr()
  2332. True
  2333. This function does not attempt any nontrivial simplifications that may
  2334. result in an expression that does not appear to be an algebraic
  2335. expression to become one.
  2336. >>> from sympy import exp, factor
  2337. >>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1)
  2338. >>> a.is_algebraic_expr(x)
  2339. False
  2340. >>> factor(a).is_algebraic_expr()
  2341. True
  2342. See Also
  2343. ========
  2344. is_rational_function()
  2345. References
  2346. ==========
  2347. .. [1] https://en.wikipedia.org/wiki/Algebraic_expression
  2348. """
  2349. if syms:
  2350. syms = set(map(sympify, syms))
  2351. else:
  2352. syms = self.free_symbols
  2353. if not syms:
  2354. return True
  2355. return self._eval_is_algebraic_expr(syms)
  2356. def _eval_is_algebraic_expr(self, syms):
  2357. if self in syms:
  2358. return True
  2359. if not self.has_free(*syms):
  2360. return True
  2361. # subclasses should return True or False
  2362. ###################################################################################
  2363. ##################### SERIES, LEADING TERM, LIMIT, ORDER METHODS ##################
  2364. ###################################################################################
  2365. def series(self, x=None, x0=0, n=6, dir="+", logx=None, cdir=0):
  2366. """
  2367. Series expansion of "self" around ``x = x0`` yielding either terms of
  2368. the series one by one (the lazy series given when n=None), else
  2369. all the terms at once when n != None.
  2370. Returns the series expansion of "self" around the point ``x = x0``
  2371. with respect to ``x`` up to ``O((x - x0)**n, x, x0)`` (default n is 6).
  2372. If ``x=None`` and ``self`` is univariate, the univariate symbol will
  2373. be supplied, otherwise an error will be raised.
  2374. Parameters
  2375. ==========
  2376. expr : Expression
  2377. The expression whose series is to be expanded.
  2378. x : Symbol
  2379. It is the variable of the expression to be calculated.
  2380. x0 : Value
  2381. The value around which ``x`` is calculated. Can be any value
  2382. from ``-oo`` to ``oo``.
  2383. n : Value
  2384. The number of terms upto which the series is to be expanded.
  2385. dir : String, optional
  2386. The series-expansion can be bi-directional. If ``dir="+"``,
  2387. then (x->x0+). If ``dir="-", then (x->x0-). For infinite
  2388. ``x0`` (``oo`` or ``-oo``), the ``dir`` argument is determined
  2389. from the direction of the infinity (i.e., ``dir="-"`` for
  2390. ``oo``).
  2391. logx : optional
  2392. It is used to replace any log(x) in the returned series with a
  2393. symbolic value rather than evaluating the actual value.
  2394. cdir : optional
  2395. It stands for complex direction, and indicates the direction
  2396. from which the expansion needs to be evaluated.
  2397. Examples
  2398. ========
  2399. >>> from sympy import cos, exp, tan
  2400. >>> from sympy.abc import x, y
  2401. >>> cos(x).series()
  2402. 1 - x**2/2 + x**4/24 + O(x**6)
  2403. >>> cos(x).series(n=4)
  2404. 1 - x**2/2 + O(x**4)
  2405. >>> cos(x).series(x, x0=1, n=2)
  2406. cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1))
  2407. >>> e = cos(x + exp(y))
  2408. >>> e.series(y, n=2)
  2409. cos(x + 1) - y*sin(x + 1) + O(y**2)
  2410. >>> e.series(x, n=2)
  2411. cos(exp(y)) - x*sin(exp(y)) + O(x**2)
  2412. If ``n=None`` then a generator of the series terms will be returned.
  2413. >>> term=cos(x).series(n=None)
  2414. >>> [next(term) for i in range(2)]
  2415. [1, -x**2/2]
  2416. For ``dir=+`` (default) the series is calculated from the right and
  2417. for ``dir=-`` the series from the left. For smooth functions this
  2418. flag will not alter the results.
  2419. >>> abs(x).series(dir="+")
  2420. x
  2421. >>> abs(x).series(dir="-")
  2422. -x
  2423. >>> f = tan(x)
  2424. >>> f.series(x, 2, 6, "+")
  2425. tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) +
  2426. (x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 +
  2427. 5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 +
  2428. 2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))
  2429. >>> f.series(x, 2, 3, "-")
  2430. tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2))
  2431. + O((x - 2)**3, (x, 2))
  2432. Returns
  2433. =======
  2434. Expr : Expression
  2435. Series expansion of the expression about x0
  2436. Raises
  2437. ======
  2438. TypeError
  2439. If "n" and "x0" are infinity objects
  2440. PoleError
  2441. If "x0" is an infinity object
  2442. """
  2443. if x is None:
  2444. syms = self.free_symbols
  2445. if not syms:
  2446. return self
  2447. elif len(syms) > 1:
  2448. raise ValueError('x must be given for multivariate functions.')
  2449. x = syms.pop()
  2450. from .symbol import Dummy, Symbol
  2451. if isinstance(x, Symbol):
  2452. dep = x in self.free_symbols
  2453. else:
  2454. d = Dummy()
  2455. dep = d in self.xreplace({x: d}).free_symbols
  2456. if not dep:
  2457. if n is None:
  2458. return (s for s in [self])
  2459. else:
  2460. return self
  2461. if len(dir) != 1 or dir not in '+-':
  2462. raise ValueError("Dir must be '+' or '-'")
  2463. if x0 in [S.Infinity, S.NegativeInfinity]:
  2464. from .function import PoleError
  2465. try:
  2466. sgn = 1 if x0 is S.Infinity else -1
  2467. s = self.subs(x, sgn/x).series(x, n=n, dir='+', cdir=cdir)
  2468. if n is None:
  2469. return (si.subs(x, sgn/x) for si in s)
  2470. return s.subs(x, sgn/x)
  2471. except PoleError:
  2472. s = self.subs(x, sgn*x).aseries(x, n=n)
  2473. return s.subs(x, sgn*x)
  2474. # use rep to shift origin to x0 and change sign (if dir is negative)
  2475. # and undo the process with rep2
  2476. if x0 or dir == '-':
  2477. if dir == '-':
  2478. rep = -x + x0
  2479. rep2 = -x
  2480. rep2b = x0
  2481. else:
  2482. rep = x + x0
  2483. rep2 = x
  2484. rep2b = -x0
  2485. s = self.subs(x, rep).series(x, x0=0, n=n, dir='+', logx=logx, cdir=cdir)
  2486. if n is None: # lseries...
  2487. return (si.subs(x, rep2 + rep2b) for si in s)
  2488. return s.subs(x, rep2 + rep2b)
  2489. # from here on it's x0=0 and dir='+' handling
  2490. if x.is_positive is x.is_negative is None or x.is_Symbol is not True:
  2491. # replace x with an x that has a positive assumption
  2492. xpos = Dummy('x', positive=True)
  2493. rv = self.subs(x, xpos).series(xpos, x0, n, dir, logx=logx, cdir=cdir)
  2494. if n is None:
  2495. return (s.subs(xpos, x) for s in rv)
  2496. else:
  2497. return rv.subs(xpos, x)
  2498. from sympy.series.order import Order
  2499. if n is not None: # nseries handling
  2500. s1 = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  2501. o = s1.getO() or S.Zero
  2502. if o:
  2503. # make sure the requested order is returned
  2504. ngot = o.getn()
  2505. if ngot > n:
  2506. # leave o in its current form (e.g. with x*log(x)) so
  2507. # it eats terms properly, then replace it below
  2508. if n != 0:
  2509. s1 += o.subs(x, x**Rational(n, ngot))
  2510. else:
  2511. s1 += Order(1, x)
  2512. elif ngot < n:
  2513. # increase the requested number of terms to get the desired
  2514. # number keep increasing (up to 9) until the received order
  2515. # is different than the original order and then predict how
  2516. # many additional terms are needed
  2517. from sympy.functions.elementary.integers import ceiling
  2518. for more in range(1, 9):
  2519. s1 = self._eval_nseries(x, n=n + more, logx=logx, cdir=cdir)
  2520. newn = s1.getn()
  2521. if newn != ngot:
  2522. ndo = n + ceiling((n - ngot)*more/(newn - ngot))
  2523. s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
  2524. while s1.getn() < n:
  2525. s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
  2526. ndo += 1
  2527. break
  2528. else:
  2529. raise ValueError('Could not calculate %s terms for %s'
  2530. % (str(n), self))
  2531. s1 += Order(x**n, x)
  2532. o = s1.getO()
  2533. s1 = s1.removeO()
  2534. elif s1.has(Order):
  2535. # asymptotic expansion
  2536. return s1
  2537. else:
  2538. o = Order(x**n, x)
  2539. s1done = s1.doit()
  2540. if (s1done + o).removeO() == s1done:
  2541. o = S.Zero
  2542. try:
  2543. from sympy.simplify.radsimp import collect
  2544. return collect(s1, x) + o
  2545. except NotImplementedError:
  2546. return s1 + o
  2547. else: # lseries handling
  2548. def yield_lseries(s):
  2549. """Return terms of lseries one at a time."""
  2550. for si in s:
  2551. if not si.is_Add:
  2552. yield si
  2553. continue
  2554. # yield terms 1 at a time if possible
  2555. # by increasing order until all the
  2556. # terms have been returned
  2557. yielded = 0
  2558. o = Order(si, x)*x
  2559. ndid = 0
  2560. ndo = len(si.args)
  2561. while 1:
  2562. do = (si - yielded + o).removeO()
  2563. o *= x
  2564. if not do or do.is_Order:
  2565. continue
  2566. if do.is_Add:
  2567. ndid += len(do.args)
  2568. else:
  2569. ndid += 1
  2570. yield do
  2571. if ndid == ndo:
  2572. break
  2573. yielded += do
  2574. return yield_lseries(self.removeO()._eval_lseries(x, logx=logx, cdir=cdir))
  2575. def aseries(self, x=None, n=6, bound=0, hir=False):
  2576. """Asymptotic Series expansion of self.
  2577. This is equivalent to ``self.series(x, oo, n)``.
  2578. Parameters
  2579. ==========
  2580. self : Expression
  2581. The expression whose series is to be expanded.
  2582. x : Symbol
  2583. It is the variable of the expression to be calculated.
  2584. n : Value
  2585. The number of terms upto which the series is to be expanded.
  2586. hir : Boolean
  2587. Set this parameter to be True to produce hierarchical series.
  2588. It stops the recursion at an early level and may provide nicer
  2589. and more useful results.
  2590. bound : Value, Integer
  2591. Use the ``bound`` parameter to give limit on rewriting
  2592. coefficients in its normalised form.
  2593. Examples
  2594. ========
  2595. >>> from sympy import sin, exp
  2596. >>> from sympy.abc import x
  2597. >>> e = sin(1/x + exp(-x)) - sin(1/x)
  2598. >>> e.aseries(x)
  2599. (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
  2600. >>> e.aseries(x, n=3, hir=True)
  2601. -exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo))
  2602. >>> e = exp(exp(x)/(1 - 1/x))
  2603. >>> e.aseries(x)
  2604. exp(exp(x)/(1 - 1/x))
  2605. >>> e.aseries(x, bound=3) # doctest: +SKIP
  2606. exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x))
  2607. Returns
  2608. =======
  2609. Expr
  2610. Asymptotic series expansion of the expression.
  2611. Notes
  2612. =====
  2613. This algorithm is directly induced from the limit computational algorithm provided by Gruntz.
  2614. It majorly uses the mrv and rewrite sub-routines. The overall idea of this algorithm is first
  2615. to look for the most rapidly varying subexpression w of a given expression f and then expands f
  2616. in a series in w. Then same thing is recursively done on the leading coefficient
  2617. till we get constant coefficients.
  2618. If the most rapidly varying subexpression of a given expression f is f itself,
  2619. the algorithm tries to find a normalised representation of the mrv set and rewrites f
  2620. using this normalised representation.
  2621. If the expansion contains an order term, it will be either ``O(x ** (-n))`` or ``O(w ** (-n))``
  2622. where ``w`` belongs to the most rapidly varying expression of ``self``.
  2623. References
  2624. ==========
  2625. .. [1] Gruntz, Dominik. A new algorithm for computing asymptotic series.
  2626. In: Proc. 1993 Int. Symp. Symbolic and Algebraic Computation. 1993.
  2627. pp. 239-244.
  2628. .. [2] Gruntz thesis - p90
  2629. .. [3] http://en.wikipedia.org/wiki/Asymptotic_expansion
  2630. See Also
  2631. ========
  2632. Expr.aseries: See the docstring of this function for complete details of this wrapper.
  2633. """
  2634. from .symbol import Dummy
  2635. if x.is_positive is x.is_negative is None:
  2636. xpos = Dummy('x', positive=True)
  2637. return self.subs(x, xpos).aseries(xpos, n, bound, hir).subs(xpos, x)
  2638. from .function import PoleError
  2639. from sympy.series.gruntz import mrv, rewrite
  2640. try:
  2641. om, exps = mrv(self, x)
  2642. except PoleError:
  2643. return self
  2644. # We move one level up by replacing `x` by `exp(x)`, and then
  2645. # computing the asymptotic series for f(exp(x)). Then asymptotic series
  2646. # can be obtained by moving one-step back, by replacing x by ln(x).
  2647. from sympy.functions.elementary.exponential import exp, log
  2648. from sympy.series.order import Order
  2649. if x in om:
  2650. s = self.subs(x, exp(x)).aseries(x, n, bound, hir).subs(x, log(x))
  2651. if s.getO():
  2652. return s + Order(1/x**n, (x, S.Infinity))
  2653. return s
  2654. k = Dummy('k', positive=True)
  2655. # f is rewritten in terms of omega
  2656. func, logw = rewrite(exps, om, x, k)
  2657. if self in om:
  2658. if bound <= 0:
  2659. return self
  2660. s = (self.exp).aseries(x, n, bound=bound)
  2661. s = s.func(*[t.removeO() for t in s.args])
  2662. try:
  2663. res = exp(s.subs(x, 1/x).as_leading_term(x).subs(x, 1/x))
  2664. except PoleError:
  2665. res = self
  2666. func = exp(self.args[0] - res.args[0]) / k
  2667. logw = log(1/res)
  2668. s = func.series(k, 0, n)
  2669. # Hierarchical series
  2670. if hir:
  2671. return s.subs(k, exp(logw))
  2672. o = s.getO()
  2673. terms = sorted(Add.make_args(s.removeO()), key=lambda i: int(i.as_coeff_exponent(k)[1]))
  2674. s = S.Zero
  2675. has_ord = False
  2676. # Then we recursively expand these coefficients one by one into
  2677. # their asymptotic series in terms of their most rapidly varying subexpressions.
  2678. for t in terms:
  2679. coeff, expo = t.as_coeff_exponent(k)
  2680. if coeff.has(x):
  2681. # Recursive step
  2682. snew = coeff.aseries(x, n, bound=bound-1)
  2683. if has_ord and snew.getO():
  2684. break
  2685. elif snew.getO():
  2686. has_ord = True
  2687. s += (snew * k**expo)
  2688. else:
  2689. s += t
  2690. if not o or has_ord:
  2691. return s.subs(k, exp(logw))
  2692. return (s + o).subs(k, exp(logw))
  2693. def taylor_term(self, n, x, *previous_terms):
  2694. """General method for the taylor term.
  2695. This method is slow, because it differentiates n-times. Subclasses can
  2696. redefine it to make it faster by using the "previous_terms".
  2697. """
  2698. from .symbol import Dummy
  2699. from sympy.functions.combinatorial.factorials import factorial
  2700. x = sympify(x)
  2701. _x = Dummy('x')
  2702. return self.subs(x, _x).diff(_x, n).subs(_x, x).subs(x, 0) * x**n / factorial(n)
  2703. def lseries(self, x=None, x0=0, dir='+', logx=None, cdir=0):
  2704. """
  2705. Wrapper for series yielding an iterator of the terms of the series.
  2706. Note: an infinite series will yield an infinite iterator. The following,
  2707. for exaxmple, will never terminate. It will just keep printing terms
  2708. of the sin(x) series::
  2709. for term in sin(x).lseries(x):
  2710. print term
  2711. The advantage of lseries() over nseries() is that many times you are
  2712. just interested in the next term in the series (i.e. the first term for
  2713. example), but you do not know how many you should ask for in nseries()
  2714. using the "n" parameter.
  2715. See also nseries().
  2716. """
  2717. return self.series(x, x0, n=None, dir=dir, logx=logx, cdir=cdir)
  2718. def _eval_lseries(self, x, logx=None, cdir=0):
  2719. # default implementation of lseries is using nseries(), and adaptively
  2720. # increasing the "n". As you can see, it is not very efficient, because
  2721. # we are calculating the series over and over again. Subclasses should
  2722. # override this method and implement much more efficient yielding of
  2723. # terms.
  2724. n = 0
  2725. series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  2726. while series.is_Order:
  2727. n += 1
  2728. series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  2729. e = series.removeO()
  2730. yield e
  2731. if e is S.Zero:
  2732. return
  2733. while 1:
  2734. while 1:
  2735. n += 1
  2736. series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir).removeO()
  2737. if e != series:
  2738. break
  2739. if (series - self).cancel() is S.Zero:
  2740. return
  2741. yield series - e
  2742. e = series
  2743. def nseries(self, x=None, x0=0, n=6, dir='+', logx=None, cdir=0):
  2744. """
  2745. Wrapper to _eval_nseries if assumptions allow, else to series.
  2746. If x is given, x0 is 0, dir='+', and self has x, then _eval_nseries is
  2747. called. This calculates "n" terms in the innermost expressions and
  2748. then builds up the final series just by "cross-multiplying" everything
  2749. out.
  2750. The optional ``logx`` parameter can be used to replace any log(x) in the
  2751. returned series with a symbolic value to avoid evaluating log(x) at 0. A
  2752. symbol to use in place of log(x) should be provided.
  2753. Advantage -- it's fast, because we do not have to determine how many
  2754. terms we need to calculate in advance.
  2755. Disadvantage -- you may end up with less terms than you may have
  2756. expected, but the O(x**n) term appended will always be correct and
  2757. so the result, though perhaps shorter, will also be correct.
  2758. If any of those assumptions is not met, this is treated like a
  2759. wrapper to series which will try harder to return the correct
  2760. number of terms.
  2761. See also lseries().
  2762. Examples
  2763. ========
  2764. >>> from sympy import sin, log, Symbol
  2765. >>> from sympy.abc import x, y
  2766. >>> sin(x).nseries(x, 0, 6)
  2767. x - x**3/6 + x**5/120 + O(x**6)
  2768. >>> log(x+1).nseries(x, 0, 5)
  2769. x - x**2/2 + x**3/3 - x**4/4 + O(x**5)
  2770. Handling of the ``logx`` parameter --- in the following example the
  2771. expansion fails since ``sin`` does not have an asymptotic expansion
  2772. at -oo (the limit of log(x) as x approaches 0):
  2773. >>> e = sin(log(x))
  2774. >>> e.nseries(x, 0, 6)
  2775. Traceback (most recent call last):
  2776. ...
  2777. PoleError: ...
  2778. ...
  2779. >>> logx = Symbol('logx')
  2780. >>> e.nseries(x, 0, 6, logx=logx)
  2781. sin(logx)
  2782. In the following example, the expansion works but gives only an Order term
  2783. unless the ``logx`` parameter is used:
  2784. >>> e = x**y
  2785. >>> e.nseries(x, 0, 2)
  2786. O(log(x)**2)
  2787. >>> e.nseries(x, 0, 2, logx=logx)
  2788. exp(logx*y)
  2789. """
  2790. if x and x not in self.free_symbols:
  2791. return self
  2792. if x is None or x0 or dir != '+': # {see XPOS above} or (x.is_positive == x.is_negative == None):
  2793. return self.series(x, x0, n, dir, cdir=cdir)
  2794. else:
  2795. return self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  2796. def _eval_nseries(self, x, n, logx, cdir):
  2797. """
  2798. Return terms of series for self up to O(x**n) at x=0
  2799. from the positive direction.
  2800. This is a method that should be overridden in subclasses. Users should
  2801. never call this method directly (use .nseries() instead), so you do not
  2802. have to write docstrings for _eval_nseries().
  2803. """
  2804. raise NotImplementedError(filldedent("""
  2805. The _eval_nseries method should be added to
  2806. %s to give terms up to O(x**n) at x=0
  2807. from the positive direction so it is available when
  2808. nseries calls it.""" % self.func)
  2809. )
  2810. def limit(self, x, xlim, dir='+'):
  2811. """ Compute limit x->xlim.
  2812. """
  2813. from sympy.series.limits import limit
  2814. return limit(self, x, xlim, dir)
  2815. def compute_leading_term(self, x, logx=None):
  2816. """
  2817. as_leading_term is only allowed for results of .series()
  2818. This is a wrapper to compute a series first.
  2819. """
  2820. from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
  2821. if self.has(Piecewise):
  2822. expr = piecewise_fold(self)
  2823. else:
  2824. expr = self
  2825. if self.removeO() == 0:
  2826. return self
  2827. from sympy.series.gruntz import calculate_series
  2828. if logx is None:
  2829. from .symbol import Dummy
  2830. from sympy.functions.elementary.exponential import log
  2831. d = Dummy('logx')
  2832. s = calculate_series(expr, x, d).subs(d, log(x))
  2833. else:
  2834. s = calculate_series(expr, x, logx)
  2835. return s.as_leading_term(x)
  2836. @cacheit
  2837. def as_leading_term(self, *symbols, logx=None, cdir=0):
  2838. """
  2839. Returns the leading (nonzero) term of the series expansion of self.
  2840. The _eval_as_leading_term routines are used to do this, and they must
  2841. always return a non-zero value.
  2842. Examples
  2843. ========
  2844. >>> from sympy.abc import x
  2845. >>> (1 + x + x**2).as_leading_term(x)
  2846. 1
  2847. >>> (1/x**2 + x + x**2).as_leading_term(x)
  2848. x**(-2)
  2849. """
  2850. if len(symbols) > 1:
  2851. c = self
  2852. for x in symbols:
  2853. c = c.as_leading_term(x, logx=logx, cdir=cdir)
  2854. return c
  2855. elif not symbols:
  2856. return self
  2857. x = sympify(symbols[0])
  2858. if not x.is_symbol:
  2859. raise ValueError('expecting a Symbol but got %s' % x)
  2860. if x not in self.free_symbols:
  2861. return self
  2862. obj = self._eval_as_leading_term(x, logx=logx, cdir=cdir)
  2863. if obj is not None:
  2864. from sympy.simplify.powsimp import powsimp
  2865. return powsimp(obj, deep=True, combine='exp')
  2866. raise NotImplementedError('as_leading_term(%s, %s)' % (self, x))
  2867. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  2868. return self
  2869. def as_coeff_exponent(self, x):
  2870. """ ``c*x**e -> c,e`` where x can be any symbolic expression.
  2871. """
  2872. from sympy.simplify.radsimp import collect
  2873. s = collect(self, x)
  2874. c, p = s.as_coeff_mul(x)
  2875. if len(p) == 1:
  2876. b, e = p[0].as_base_exp()
  2877. if b == x:
  2878. return c, e
  2879. return s, S.Zero
  2880. def leadterm(self, x, logx=None, cdir=0):
  2881. """
  2882. Returns the leading term a*x**b as a tuple (a, b).
  2883. Examples
  2884. ========
  2885. >>> from sympy.abc import x
  2886. >>> (1+x+x**2).leadterm(x)
  2887. (1, 0)
  2888. >>> (1/x**2+x+x**2).leadterm(x)
  2889. (1, -2)
  2890. """
  2891. from .symbol import Dummy
  2892. from sympy.functions.elementary.exponential import log
  2893. l = self.as_leading_term(x, logx=logx, cdir=cdir)
  2894. d = Dummy('logx')
  2895. if l.has(log(x)):
  2896. l = l.subs(log(x), d)
  2897. c, e = l.as_coeff_exponent(x)
  2898. if x in c.free_symbols:
  2899. raise ValueError(filldedent("""
  2900. cannot compute leadterm(%s, %s). The coefficient
  2901. should have been free of %s but got %s""" % (self, x, x, c)))
  2902. c = c.subs(d, log(x))
  2903. return c, e
  2904. def as_coeff_Mul(self, rational=False):
  2905. """Efficiently extract the coefficient of a product. """
  2906. return S.One, self
  2907. def as_coeff_Add(self, rational=False):
  2908. """Efficiently extract the coefficient of a summation. """
  2909. return S.Zero, self
  2910. def fps(self, x=None, x0=0, dir=1, hyper=True, order=4, rational=True,
  2911. full=False):
  2912. """
  2913. Compute formal power power series of self.
  2914. See the docstring of the :func:`fps` function in sympy.series.formal for
  2915. more information.
  2916. """
  2917. from sympy.series.formal import fps
  2918. return fps(self, x, x0, dir, hyper, order, rational, full)
  2919. def fourier_series(self, limits=None):
  2920. """Compute fourier sine/cosine series of self.
  2921. See the docstring of the :func:`fourier_series` in sympy.series.fourier
  2922. for more information.
  2923. """
  2924. from sympy.series.fourier import fourier_series
  2925. return fourier_series(self, limits)
  2926. ###################################################################################
  2927. ##################### DERIVATIVE, INTEGRAL, FUNCTIONAL METHODS ####################
  2928. ###################################################################################
  2929. def diff(self, *symbols, **assumptions):
  2930. assumptions.setdefault("evaluate", True)
  2931. return _derivative_dispatch(self, *symbols, **assumptions)
  2932. ###########################################################################
  2933. ###################### EXPRESSION EXPANSION METHODS #######################
  2934. ###########################################################################
  2935. # Relevant subclasses should override _eval_expand_hint() methods. See
  2936. # the docstring of expand() for more info.
  2937. def _eval_expand_complex(self, **hints):
  2938. real, imag = self.as_real_imag(**hints)
  2939. return real + S.ImaginaryUnit*imag
  2940. @staticmethod
  2941. def _expand_hint(expr, hint, deep=True, **hints):
  2942. """
  2943. Helper for ``expand()``. Recursively calls ``expr._eval_expand_hint()``.
  2944. Returns ``(expr, hit)``, where expr is the (possibly) expanded
  2945. ``expr`` and ``hit`` is ``True`` if ``expr`` was truly expanded and
  2946. ``False`` otherwise.
  2947. """
  2948. hit = False
  2949. # XXX: Hack to support non-Basic args
  2950. # |
  2951. # V
  2952. if deep and getattr(expr, 'args', ()) and not expr.is_Atom:
  2953. sargs = []
  2954. for arg in expr.args:
  2955. arg, arghit = Expr._expand_hint(arg, hint, **hints)
  2956. hit |= arghit
  2957. sargs.append(arg)
  2958. if hit:
  2959. expr = expr.func(*sargs)
  2960. if hasattr(expr, hint):
  2961. newexpr = getattr(expr, hint)(**hints)
  2962. if newexpr != expr:
  2963. return (newexpr, True)
  2964. return (expr, hit)
  2965. @cacheit
  2966. def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
  2967. mul=True, log=True, multinomial=True, basic=True, **hints):
  2968. """
  2969. Expand an expression using hints.
  2970. See the docstring of the expand() function in sympy.core.function for
  2971. more information.
  2972. """
  2973. from sympy.simplify.radsimp import fraction
  2974. hints.update(power_base=power_base, power_exp=power_exp, mul=mul,
  2975. log=log, multinomial=multinomial, basic=basic)
  2976. expr = self
  2977. if hints.pop('frac', False):
  2978. n, d = [a.expand(deep=deep, modulus=modulus, **hints)
  2979. for a in fraction(self)]
  2980. return n/d
  2981. elif hints.pop('denom', False):
  2982. n, d = fraction(self)
  2983. return n/d.expand(deep=deep, modulus=modulus, **hints)
  2984. elif hints.pop('numer', False):
  2985. n, d = fraction(self)
  2986. return n.expand(deep=deep, modulus=modulus, **hints)/d
  2987. # Although the hints are sorted here, an earlier hint may get applied
  2988. # at a given node in the expression tree before another because of how
  2989. # the hints are applied. e.g. expand(log(x*(y + z))) -> log(x*y +
  2990. # x*z) because while applying log at the top level, log and mul are
  2991. # applied at the deeper level in the tree so that when the log at the
  2992. # upper level gets applied, the mul has already been applied at the
  2993. # lower level.
  2994. # Additionally, because hints are only applied once, the expression
  2995. # may not be expanded all the way. For example, if mul is applied
  2996. # before multinomial, x*(x + 1)**2 won't be expanded all the way. For
  2997. # now, we just use a special case to make multinomial run before mul,
  2998. # so that at least polynomials will be expanded all the way. In the
  2999. # future, smarter heuristics should be applied.
  3000. # TODO: Smarter heuristics
  3001. def _expand_hint_key(hint):
  3002. """Make multinomial come before mul"""
  3003. if hint == 'mul':
  3004. return 'mulz'
  3005. return hint
  3006. for hint in sorted(hints.keys(), key=_expand_hint_key):
  3007. use_hint = hints[hint]
  3008. if use_hint:
  3009. hint = '_eval_expand_' + hint
  3010. expr, hit = Expr._expand_hint(expr, hint, deep=deep, **hints)
  3011. while True:
  3012. was = expr
  3013. if hints.get('multinomial', False):
  3014. expr, _ = Expr._expand_hint(
  3015. expr, '_eval_expand_multinomial', deep=deep, **hints)
  3016. if hints.get('mul', False):
  3017. expr, _ = Expr._expand_hint(
  3018. expr, '_eval_expand_mul', deep=deep, **hints)
  3019. if hints.get('log', False):
  3020. expr, _ = Expr._expand_hint(
  3021. expr, '_eval_expand_log', deep=deep, **hints)
  3022. if expr == was:
  3023. break
  3024. if modulus is not None:
  3025. modulus = sympify(modulus)
  3026. if not modulus.is_Integer or modulus <= 0:
  3027. raise ValueError(
  3028. "modulus must be a positive integer, got %s" % modulus)
  3029. terms = []
  3030. for term in Add.make_args(expr):
  3031. coeff, tail = term.as_coeff_Mul(rational=True)
  3032. coeff %= modulus
  3033. if coeff:
  3034. terms.append(coeff*tail)
  3035. expr = Add(*terms)
  3036. return expr
  3037. ###########################################################################
  3038. ################### GLOBAL ACTION VERB WRAPPER METHODS ####################
  3039. ###########################################################################
  3040. def integrate(self, *args, **kwargs):
  3041. """See the integrate function in sympy.integrals"""
  3042. from sympy.integrals.integrals import integrate
  3043. return integrate(self, *args, **kwargs)
  3044. def nsimplify(self, constants=(), tolerance=None, full=False):
  3045. """See the nsimplify function in sympy.simplify"""
  3046. from sympy.simplify.simplify import nsimplify
  3047. return nsimplify(self, constants, tolerance, full)
  3048. def separate(self, deep=False, force=False):
  3049. """See the separate function in sympy.simplify"""
  3050. from .function import expand_power_base
  3051. return expand_power_base(self, deep=deep, force=force)
  3052. def collect(self, syms, func=None, evaluate=True, exact=False, distribute_order_term=True):
  3053. """See the collect function in sympy.simplify"""
  3054. from sympy.simplify.radsimp import collect
  3055. return collect(self, syms, func, evaluate, exact, distribute_order_term)
  3056. def together(self, *args, **kwargs):
  3057. """See the together function in sympy.polys"""
  3058. from sympy.polys.rationaltools import together
  3059. return together(self, *args, **kwargs)
  3060. def apart(self, x=None, **args):
  3061. """See the apart function in sympy.polys"""
  3062. from sympy.polys.partfrac import apart
  3063. return apart(self, x, **args)
  3064. def ratsimp(self):
  3065. """See the ratsimp function in sympy.simplify"""
  3066. from sympy.simplify.ratsimp import ratsimp
  3067. return ratsimp(self)
  3068. def trigsimp(self, **args):
  3069. """See the trigsimp function in sympy.simplify"""
  3070. from sympy.simplify.trigsimp import trigsimp
  3071. return trigsimp(self, **args)
  3072. def radsimp(self, **kwargs):
  3073. """See the radsimp function in sympy.simplify"""
  3074. from sympy.simplify.radsimp import radsimp
  3075. return radsimp(self, **kwargs)
  3076. def powsimp(self, *args, **kwargs):
  3077. """See the powsimp function in sympy.simplify"""
  3078. from sympy.simplify.powsimp import powsimp
  3079. return powsimp(self, *args, **kwargs)
  3080. def combsimp(self):
  3081. """See the combsimp function in sympy.simplify"""
  3082. from sympy.simplify.combsimp import combsimp
  3083. return combsimp(self)
  3084. def gammasimp(self):
  3085. """See the gammasimp function in sympy.simplify"""
  3086. from sympy.simplify.gammasimp import gammasimp
  3087. return gammasimp(self)
  3088. def factor(self, *gens, **args):
  3089. """See the factor() function in sympy.polys.polytools"""
  3090. from sympy.polys.polytools import factor
  3091. return factor(self, *gens, **args)
  3092. def cancel(self, *gens, **args):
  3093. """See the cancel function in sympy.polys"""
  3094. from sympy.polys.polytools import cancel
  3095. return cancel(self, *gens, **args)
  3096. def invert(self, g, *gens, **args):
  3097. """Return the multiplicative inverse of ``self`` mod ``g``
  3098. where ``self`` (and ``g``) may be symbolic expressions).
  3099. See Also
  3100. ========
  3101. sympy.core.numbers.mod_inverse, sympy.polys.polytools.invert
  3102. """
  3103. if self.is_number and getattr(g, 'is_number', True):
  3104. from .numbers import mod_inverse
  3105. return mod_inverse(self, g)
  3106. from sympy.polys.polytools import invert
  3107. return invert(self, g, *gens, **args)
  3108. def round(self, n=None):
  3109. """Return x rounded to the given decimal place.
  3110. If a complex number would results, apply round to the real
  3111. and imaginary components of the number.
  3112. Examples
  3113. ========
  3114. >>> from sympy import pi, E, I, S, Number
  3115. >>> pi.round()
  3116. 3
  3117. >>> pi.round(2)
  3118. 3.14
  3119. >>> (2*pi + E*I).round()
  3120. 6 + 3*I
  3121. The round method has a chopping effect:
  3122. >>> (2*pi + I/10).round()
  3123. 6
  3124. >>> (pi/10 + 2*I).round()
  3125. 2*I
  3126. >>> (pi/10 + E*I).round(2)
  3127. 0.31 + 2.72*I
  3128. Notes
  3129. =====
  3130. The Python ``round`` function uses the SymPy ``round`` method so it
  3131. will always return a SymPy number (not a Python float or int):
  3132. >>> isinstance(round(S(123), -2), Number)
  3133. True
  3134. """
  3135. from sympy.core.numbers import Float
  3136. x = self
  3137. if not x.is_number:
  3138. raise TypeError("Cannot round symbolic expression")
  3139. if not x.is_Atom:
  3140. if not pure_complex(x.n(2), or_real=True):
  3141. raise TypeError(
  3142. 'Expected a number but got %s:' % func_name(x))
  3143. elif x in (S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity):
  3144. return x
  3145. if x.is_extended_real is False:
  3146. r, i = x.as_real_imag()
  3147. return r.round(n) + S.ImaginaryUnit*i.round(n)
  3148. if not x:
  3149. return S.Zero if n is None else x
  3150. p = as_int(n or 0)
  3151. if x.is_Integer:
  3152. return Integer(round(int(x), p))
  3153. digits_to_decimal = _mag(x) # _mag(12) = 2, _mag(.012) = -1
  3154. allow = digits_to_decimal + p
  3155. precs = [f._prec for f in x.atoms(Float)]
  3156. dps = prec_to_dps(max(precs)) if precs else None
  3157. if dps is None:
  3158. # assume everything is exact so use the Python
  3159. # float default or whatever was requested
  3160. dps = max(15, allow)
  3161. else:
  3162. allow = min(allow, dps)
  3163. # this will shift all digits to right of decimal
  3164. # and give us dps to work with as an int
  3165. shift = -digits_to_decimal + dps
  3166. extra = 1 # how far we look past known digits
  3167. # NOTE
  3168. # mpmath will calculate the binary representation to
  3169. # an arbitrary number of digits but we must base our
  3170. # answer on a finite number of those digits, e.g.
  3171. # .575 2589569785738035/2**52 in binary.
  3172. # mpmath shows us that the first 18 digits are
  3173. # >>> Float(.575).n(18)
  3174. # 0.574999999999999956
  3175. # The default precision is 15 digits and if we ask
  3176. # for 15 we get
  3177. # >>> Float(.575).n(15)
  3178. # 0.575000000000000
  3179. # mpmath handles rounding at the 15th digit. But we
  3180. # need to be careful since the user might be asking
  3181. # for rounding at the last digit and our semantics
  3182. # are to round toward the even final digit when there
  3183. # is a tie. So the extra digit will be used to make
  3184. # that decision. In this case, the value is the same
  3185. # to 15 digits:
  3186. # >>> Float(.575).n(16)
  3187. # 0.5750000000000000
  3188. # Now converting this to the 15 known digits gives
  3189. # 575000000000000.0
  3190. # which rounds to integer
  3191. # 5750000000000000
  3192. # And now we can round to the desired digt, e.g. at
  3193. # the second from the left and we get
  3194. # 5800000000000000
  3195. # and rescaling that gives
  3196. # 0.58
  3197. # as the final result.
  3198. # If the value is made slightly less than 0.575 we might
  3199. # still obtain the same value:
  3200. # >>> Float(.575-1e-16).n(16)*10**15
  3201. # 574999999999999.8
  3202. # What 15 digits best represents the known digits (which are
  3203. # to the left of the decimal? 5750000000000000, the same as
  3204. # before. The only way we will round down (in this case) is
  3205. # if we declared that we had more than 15 digits of precision.
  3206. # For example, if we use 16 digits of precision, the integer
  3207. # we deal with is
  3208. # >>> Float(.575-1e-16).n(17)*10**16
  3209. # 5749999999999998.4
  3210. # and this now rounds to 5749999999999998 and (if we round to
  3211. # the 2nd digit from the left) we get 5700000000000000.
  3212. #
  3213. xf = x.n(dps + extra)*Pow(10, shift)
  3214. xi = Integer(xf)
  3215. # use the last digit to select the value of xi
  3216. # nearest to x before rounding at the desired digit
  3217. sign = 1 if x > 0 else -1
  3218. dif2 = sign*(xf - xi).n(extra)
  3219. if dif2 < 0:
  3220. raise NotImplementedError(
  3221. 'not expecting int(x) to round away from 0')
  3222. if dif2 > .5:
  3223. xi += sign # round away from 0
  3224. elif dif2 == .5:
  3225. xi += sign if xi%2 else -sign # round toward even
  3226. # shift p to the new position
  3227. ip = p - shift
  3228. # let Python handle the int rounding then rescale
  3229. xr = round(xi.p, ip)
  3230. # restore scale
  3231. rv = Rational(xr, Pow(10, shift))
  3232. # return Float or Integer
  3233. if rv.is_Integer:
  3234. if n is None: # the single-arg case
  3235. return rv
  3236. # use str or else it won't be a float
  3237. return Float(str(rv), dps) # keep same precision
  3238. else:
  3239. if not allow and rv > self:
  3240. allow += 1
  3241. return Float(rv, allow)
  3242. __round__ = round
  3243. def _eval_derivative_matrix_lines(self, x):
  3244. from sympy.matrices.expressions.matexpr import _LeftRightArgs
  3245. return [_LeftRightArgs([S.One, S.One], higher=self._eval_derivative(x))]
  3246. class AtomicExpr(Atom, Expr):
  3247. """
  3248. A parent class for object which are both atoms and Exprs.
  3249. For example: Symbol, Number, Rational, Integer, ...
  3250. But not: Add, Mul, Pow, ...
  3251. """
  3252. is_number = False
  3253. is_Atom = True
  3254. __slots__ = ()
  3255. def _eval_derivative(self, s):
  3256. if self == s:
  3257. return S.One
  3258. return S.Zero
  3259. def _eval_derivative_n_times(self, s, n):
  3260. from .containers import Tuple
  3261. from sympy.matrices.expressions.matexpr import MatrixExpr
  3262. from sympy.matrices.common import MatrixCommon
  3263. if isinstance(s, (MatrixCommon, Tuple, Iterable, MatrixExpr)):
  3264. return super()._eval_derivative_n_times(s, n)
  3265. from .relational import Eq
  3266. from sympy.functions.elementary.piecewise import Piecewise
  3267. if self == s:
  3268. return Piecewise((self, Eq(n, 0)), (1, Eq(n, 1)), (0, True))
  3269. else:
  3270. return Piecewise((self, Eq(n, 0)), (0, True))
  3271. def _eval_is_polynomial(self, syms):
  3272. return True
  3273. def _eval_is_rational_function(self, syms):
  3274. return True
  3275. def _eval_is_meromorphic(self, x, a):
  3276. from sympy.calculus.accumulationbounds import AccumBounds
  3277. return (not self.is_Number or self.is_finite) and not isinstance(self, AccumBounds)
  3278. def _eval_is_algebraic_expr(self, syms):
  3279. return True
  3280. def _eval_nseries(self, x, n, logx, cdir=0):
  3281. return self
  3282. @property
  3283. def expr_free_symbols(self):
  3284. sympy_deprecation_warning("""
  3285. The expr_free_symbols property is deprecated. Use free_symbols to get
  3286. the free symbols of an expression.
  3287. """,
  3288. deprecated_since_version="1.9",
  3289. active_deprecations_target="deprecated-expr-free-symbols")
  3290. return {self}
  3291. def _mag(x):
  3292. r"""Return integer $i$ such that $0.1 \le x/10^i < 1$
  3293. Examples
  3294. ========
  3295. >>> from sympy.core.expr import _mag
  3296. >>> from sympy import Float
  3297. >>> _mag(Float(.1))
  3298. 0
  3299. >>> _mag(Float(.01))
  3300. -1
  3301. >>> _mag(Float(1234))
  3302. 4
  3303. """
  3304. from math import log10, ceil, log
  3305. xpos = abs(x.n())
  3306. if not xpos:
  3307. return S.Zero
  3308. try:
  3309. mag_first_dig = int(ceil(log10(xpos)))
  3310. except (ValueError, OverflowError):
  3311. from .numbers import Float
  3312. mag_first_dig = int(ceil(Float(mpf_log(xpos._mpf_, 53))/log(10)))
  3313. # check that we aren't off by 1
  3314. if (xpos/10**mag_first_dig) >= 1:
  3315. assert 1 <= (xpos/10**mag_first_dig) < 10
  3316. mag_first_dig += 1
  3317. return mag_first_dig
  3318. class UnevaluatedExpr(Expr):
  3319. """
  3320. Expression that is not evaluated unless released.
  3321. Examples
  3322. ========
  3323. >>> from sympy import UnevaluatedExpr
  3324. >>> from sympy.abc import x
  3325. >>> x*(1/x)
  3326. 1
  3327. >>> x*UnevaluatedExpr(1/x)
  3328. x*1/x
  3329. """
  3330. def __new__(cls, arg, **kwargs):
  3331. arg = _sympify(arg)
  3332. obj = Expr.__new__(cls, arg, **kwargs)
  3333. return obj
  3334. def doit(self, **kwargs):
  3335. if kwargs.get("deep", True):
  3336. return self.args[0].doit(**kwargs)
  3337. else:
  3338. return self.args[0]
  3339. def unchanged(func, *args):
  3340. """Return True if `func` applied to the `args` is unchanged.
  3341. Can be used instead of `assert foo == foo`.
  3342. Examples
  3343. ========
  3344. >>> from sympy import Piecewise, cos, pi
  3345. >>> from sympy.core.expr import unchanged
  3346. >>> from sympy.abc import x
  3347. >>> unchanged(cos, 1) # instead of assert cos(1) == cos(1)
  3348. True
  3349. >>> unchanged(cos, pi)
  3350. False
  3351. Comparison of args uses the builtin capabilities of the object's
  3352. arguments to test for equality so args can be defined loosely. Here,
  3353. the ExprCondPair arguments of Piecewise compare as equal to the
  3354. tuples that can be used to create the Piecewise:
  3355. >>> unchanged(Piecewise, (x, x > 1), (0, True))
  3356. True
  3357. """
  3358. f = func(*args)
  3359. return f.func == func and f.args == args
  3360. class ExprBuilder:
  3361. def __init__(self, op, args=None, validator=None, check=True):
  3362. if not hasattr(op, "__call__"):
  3363. raise TypeError("op {} needs to be callable".format(op))
  3364. self.op = op
  3365. if args is None:
  3366. self.args = []
  3367. else:
  3368. self.args = args
  3369. self.validator = validator
  3370. if (validator is not None) and check:
  3371. self.validate()
  3372. @staticmethod
  3373. def _build_args(args):
  3374. return [i.build() if isinstance(i, ExprBuilder) else i for i in args]
  3375. def validate(self):
  3376. if self.validator is None:
  3377. return
  3378. args = self._build_args(self.args)
  3379. self.validator(*args)
  3380. def build(self, check=True):
  3381. args = self._build_args(self.args)
  3382. if self.validator and check:
  3383. self.validator(*args)
  3384. return self.op(*args)
  3385. def append_argument(self, arg, check=True):
  3386. self.args.append(arg)
  3387. if self.validator and check:
  3388. self.validate(*self.args)
  3389. def __getitem__(self, item):
  3390. if item == 0:
  3391. return self.op
  3392. else:
  3393. return self.args[item-1]
  3394. def __repr__(self):
  3395. return str(self.build())
  3396. def search_element(self, elem):
  3397. for i, arg in enumerate(self.args):
  3398. if isinstance(arg, ExprBuilder):
  3399. ret = arg.search_index(elem)
  3400. if ret is not None:
  3401. return (i,) + ret
  3402. elif id(arg) == id(elem):
  3403. return (i,)
  3404. return None
  3405. from .mul import Mul
  3406. from .add import Add
  3407. from .power import Pow
  3408. from .function import Function, _derivative_dispatch
  3409. from .mod import Mod
  3410. from .exprtools import factor_terms
  3411. from .numbers import Integer, Rational