miscellaneous.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. from sympy.core import Function, S, sympify, NumberKind
  2. from sympy.utilities.iterables import sift
  3. from sympy.core.add import Add
  4. from sympy.core.containers import Tuple
  5. from sympy.core.operations import LatticeOp, ShortCircuit
  6. from sympy.core.function import (Application, Lambda,
  7. ArgumentIndexError)
  8. from sympy.core.expr import Expr
  9. from sympy.core.exprtools import factor_terms
  10. from sympy.core.mod import Mod
  11. from sympy.core.mul import Mul
  12. from sympy.core.numbers import Rational
  13. from sympy.core.power import Pow
  14. from sympy.core.relational import Eq, Relational
  15. from sympy.core.singleton import Singleton
  16. from sympy.core.sorting import ordered
  17. from sympy.core.symbol import Dummy
  18. from sympy.core.rules import Transform
  19. from sympy.core.logic import fuzzy_and, fuzzy_or, _torf
  20. from sympy.core.traversal import walk
  21. from sympy.core.numbers import Integer
  22. from sympy.logic.boolalg import And, Or
  23. def _minmax_as_Piecewise(op, *args):
  24. # helper for Min/Max rewrite as Piecewise
  25. from sympy.functions.elementary.piecewise import Piecewise
  26. ec = []
  27. for i, a in enumerate(args):
  28. c = []
  29. for j in range(i + 1, len(args)):
  30. c.append(Relational(a, args[j], op))
  31. ec.append((a, And(*c)))
  32. return Piecewise(*ec)
  33. class IdentityFunction(Lambda, metaclass=Singleton):
  34. """
  35. The identity function
  36. Examples
  37. ========
  38. >>> from sympy import Id, Symbol
  39. >>> x = Symbol('x')
  40. >>> Id(x)
  41. x
  42. """
  43. _symbol = Dummy('x')
  44. @property
  45. def signature(self):
  46. return Tuple(self._symbol)
  47. @property
  48. def expr(self):
  49. return self._symbol
  50. Id = S.IdentityFunction
  51. ###############################################################################
  52. ############################# ROOT and SQUARE ROOT FUNCTION ###################
  53. ###############################################################################
  54. def sqrt(arg, evaluate=None):
  55. """Returns the principal square root.
  56. Parameters
  57. ==========
  58. evaluate : bool, optional
  59. The parameter determines if the expression should be evaluated.
  60. If ``None``, its value is taken from
  61. ``global_parameters.evaluate``.
  62. Examples
  63. ========
  64. >>> from sympy import sqrt, Symbol, S
  65. >>> x = Symbol('x')
  66. >>> sqrt(x)
  67. sqrt(x)
  68. >>> sqrt(x)**2
  69. x
  70. Note that sqrt(x**2) does not simplify to x.
  71. >>> sqrt(x**2)
  72. sqrt(x**2)
  73. This is because the two are not equal to each other in general.
  74. For example, consider x == -1:
  75. >>> from sympy import Eq
  76. >>> Eq(sqrt(x**2), x).subs(x, -1)
  77. False
  78. This is because sqrt computes the principal square root, so the square may
  79. put the argument in a different branch. This identity does hold if x is
  80. positive:
  81. >>> y = Symbol('y', positive=True)
  82. >>> sqrt(y**2)
  83. y
  84. You can force this simplification by using the powdenest() function with
  85. the force option set to True:
  86. >>> from sympy import powdenest
  87. >>> sqrt(x**2)
  88. sqrt(x**2)
  89. >>> powdenest(sqrt(x**2), force=True)
  90. x
  91. To get both branches of the square root you can use the rootof function:
  92. >>> from sympy import rootof
  93. >>> [rootof(x**2-3,i) for i in (0,1)]
  94. [-sqrt(3), sqrt(3)]
  95. Although ``sqrt`` is printed, there is no ``sqrt`` function so looking for
  96. ``sqrt`` in an expression will fail:
  97. >>> from sympy.utilities.misc import func_name
  98. >>> func_name(sqrt(x))
  99. 'Pow'
  100. >>> sqrt(x).has(sqrt)
  101. False
  102. To find ``sqrt`` look for ``Pow`` with an exponent of ``1/2``:
  103. >>> (x + 1/sqrt(x)).find(lambda i: i.is_Pow and abs(i.exp) is S.Half)
  104. {1/sqrt(x)}
  105. See Also
  106. ========
  107. sympy.polys.rootoftools.rootof, root, real_root
  108. References
  109. ==========
  110. .. [1] https://en.wikipedia.org/wiki/Square_root
  111. .. [2] https://en.wikipedia.org/wiki/Principal_value
  112. """
  113. # arg = sympify(arg) is handled by Pow
  114. return Pow(arg, S.Half, evaluate=evaluate)
  115. def cbrt(arg, evaluate=None):
  116. """Returns the principal cube root.
  117. Parameters
  118. ==========
  119. evaluate : bool, optional
  120. The parameter determines if the expression should be evaluated.
  121. If ``None``, its value is taken from
  122. ``global_parameters.evaluate``.
  123. Examples
  124. ========
  125. >>> from sympy import cbrt, Symbol
  126. >>> x = Symbol('x')
  127. >>> cbrt(x)
  128. x**(1/3)
  129. >>> cbrt(x)**3
  130. x
  131. Note that cbrt(x**3) does not simplify to x.
  132. >>> cbrt(x**3)
  133. (x**3)**(1/3)
  134. This is because the two are not equal to each other in general.
  135. For example, consider `x == -1`:
  136. >>> from sympy import Eq
  137. >>> Eq(cbrt(x**3), x).subs(x, -1)
  138. False
  139. This is because cbrt computes the principal cube root, this
  140. identity does hold if `x` is positive:
  141. >>> y = Symbol('y', positive=True)
  142. >>> cbrt(y**3)
  143. y
  144. See Also
  145. ========
  146. sympy.polys.rootoftools.rootof, root, real_root
  147. References
  148. ==========
  149. .. [1] https://en.wikipedia.org/wiki/Cube_root
  150. .. [2] https://en.wikipedia.org/wiki/Principal_value
  151. """
  152. return Pow(arg, Rational(1, 3), evaluate=evaluate)
  153. def root(arg, n, k=0, evaluate=None):
  154. r"""Returns the *k*-th *n*-th root of ``arg``.
  155. Parameters
  156. ==========
  157. k : int, optional
  158. Should be an integer in $\{0, 1, ..., n-1\}$.
  159. Defaults to the principal root if $0$.
  160. evaluate : bool, optional
  161. The parameter determines if the expression should be evaluated.
  162. If ``None``, its value is taken from
  163. ``global_parameters.evaluate``.
  164. Examples
  165. ========
  166. >>> from sympy import root, Rational
  167. >>> from sympy.abc import x, n
  168. >>> root(x, 2)
  169. sqrt(x)
  170. >>> root(x, 3)
  171. x**(1/3)
  172. >>> root(x, n)
  173. x**(1/n)
  174. >>> root(x, -Rational(2, 3))
  175. x**(-3/2)
  176. To get the k-th n-th root, specify k:
  177. >>> root(-2, 3, 2)
  178. -(-1)**(2/3)*2**(1/3)
  179. To get all n n-th roots you can use the rootof function.
  180. The following examples show the roots of unity for n
  181. equal 2, 3 and 4:
  182. >>> from sympy import rootof
  183. >>> [rootof(x**2 - 1, i) for i in range(2)]
  184. [-1, 1]
  185. >>> [rootof(x**3 - 1,i) for i in range(3)]
  186. [1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]
  187. >>> [rootof(x**4 - 1,i) for i in range(4)]
  188. [-1, 1, -I, I]
  189. SymPy, like other symbolic algebra systems, returns the
  190. complex root of negative numbers. This is the principal
  191. root and differs from the text-book result that one might
  192. be expecting. For example, the cube root of -8 does not
  193. come back as -2:
  194. >>> root(-8, 3)
  195. 2*(-1)**(1/3)
  196. The real_root function can be used to either make the principal
  197. result real (or simply to return the real root directly):
  198. >>> from sympy import real_root
  199. >>> real_root(_)
  200. -2
  201. >>> real_root(-32, 5)
  202. -2
  203. Alternatively, the n//2-th n-th root of a negative number can be
  204. computed with root:
  205. >>> root(-32, 5, 5//2)
  206. -2
  207. See Also
  208. ========
  209. sympy.polys.rootoftools.rootof
  210. sympy.core.power.integer_nthroot
  211. sqrt, real_root
  212. References
  213. ==========
  214. .. [1] https://en.wikipedia.org/wiki/Square_root
  215. .. [2] https://en.wikipedia.org/wiki/Real_root
  216. .. [3] https://en.wikipedia.org/wiki/Root_of_unity
  217. .. [4] https://en.wikipedia.org/wiki/Principal_value
  218. .. [5] http://mathworld.wolfram.com/CubeRoot.html
  219. """
  220. n = sympify(n)
  221. if k:
  222. return Mul(Pow(arg, S.One/n, evaluate=evaluate), S.NegativeOne**(2*k/n), evaluate=evaluate)
  223. return Pow(arg, 1/n, evaluate=evaluate)
  224. def real_root(arg, n=None, evaluate=None):
  225. r"""Return the real *n*'th-root of *arg* if possible.
  226. Parameters
  227. ==========
  228. n : int or None, optional
  229. If *n* is ``None``, then all instances of
  230. $(-n)^{1/\text{odd}}$ will be changed to $-n^{1/\text{odd}}$.
  231. This will only create a real root of a principal root.
  232. The presence of other factors may cause the result to not be
  233. real.
  234. evaluate : bool, optional
  235. The parameter determines if the expression should be evaluated.
  236. If ``None``, its value is taken from
  237. ``global_parameters.evaluate``.
  238. Examples
  239. ========
  240. >>> from sympy import root, real_root
  241. >>> real_root(-8, 3)
  242. -2
  243. >>> root(-8, 3)
  244. 2*(-1)**(1/3)
  245. >>> real_root(_)
  246. -2
  247. If one creates a non-principal root and applies real_root, the
  248. result will not be real (so use with caution):
  249. >>> root(-8, 3, 2)
  250. -2*(-1)**(2/3)
  251. >>> real_root(_)
  252. -2*(-1)**(2/3)
  253. See Also
  254. ========
  255. sympy.polys.rootoftools.rootof
  256. sympy.core.power.integer_nthroot
  257. root, sqrt
  258. """
  259. from sympy.functions.elementary.complexes import Abs, im, sign
  260. from sympy.functions.elementary.piecewise import Piecewise
  261. if n is not None:
  262. return Piecewise(
  263. (root(arg, n, evaluate=evaluate), Or(Eq(n, S.One), Eq(n, S.NegativeOne))),
  264. (Mul(sign(arg), root(Abs(arg), n, evaluate=evaluate), evaluate=evaluate),
  265. And(Eq(im(arg), S.Zero), Eq(Mod(n, 2), S.One))),
  266. (root(arg, n, evaluate=evaluate), True))
  267. rv = sympify(arg)
  268. n1pow = Transform(lambda x: -(-x.base)**x.exp,
  269. lambda x:
  270. x.is_Pow and
  271. x.base.is_negative and
  272. x.exp.is_Rational and
  273. x.exp.p == 1 and x.exp.q % 2)
  274. return rv.xreplace(n1pow)
  275. ###############################################################################
  276. ############################# MINIMUM and MAXIMUM #############################
  277. ###############################################################################
  278. class MinMaxBase(Expr, LatticeOp):
  279. def __new__(cls, *args, **assumptions):
  280. evaluate = assumptions.pop('evaluate', True)
  281. args = (sympify(arg) for arg in args)
  282. # first standard filter, for cls.zero and cls.identity
  283. # also reshape Max(a, Max(b, c)) to Max(a, b, c)
  284. if evaluate:
  285. try:
  286. args = frozenset(cls._new_args_filter(args))
  287. except ShortCircuit:
  288. return cls.zero
  289. else:
  290. args = frozenset(args)
  291. if evaluate:
  292. # remove redundant args that are easily identified
  293. args = cls._collapse_arguments(args, **assumptions)
  294. # find local zeros
  295. args = cls._find_localzeros(args, **assumptions)
  296. if not args:
  297. return cls.identity
  298. if len(args) == 1:
  299. return list(args).pop()
  300. # base creation
  301. _args = frozenset(args)
  302. obj = Expr.__new__(cls, *ordered(_args), **assumptions)
  303. obj._argset = _args
  304. return obj
  305. @classmethod
  306. def _collapse_arguments(cls, args, **assumptions):
  307. """Remove redundant args.
  308. Examples
  309. ========
  310. >>> from sympy import Min, Max
  311. >>> from sympy.abc import a, b, c, d, e
  312. Any arg in parent that appears in any
  313. parent-like function in any of the flat args
  314. of parent can be removed from that sub-arg:
  315. >>> Min(a, Max(b, Min(a, c, d)))
  316. Min(a, Max(b, Min(c, d)))
  317. If the arg of parent appears in an opposite-than parent
  318. function in any of the flat args of parent that function
  319. can be replaced with the arg:
  320. >>> Min(a, Max(b, Min(c, d, Max(a, e))))
  321. Min(a, Max(b, Min(a, c, d)))
  322. """
  323. if not args:
  324. return args
  325. args = list(ordered(args))
  326. if cls == Min:
  327. other = Max
  328. else:
  329. other = Min
  330. # find global comparable max of Max and min of Min if a new
  331. # value is being introduced in these args at position 0 of
  332. # the ordered args
  333. if args[0].is_number:
  334. sifted = mins, maxs = [], []
  335. for i in args:
  336. for v in walk(i, Min, Max):
  337. if v.args[0].is_comparable:
  338. sifted[isinstance(v, Max)].append(v)
  339. small = Min.identity
  340. for i in mins:
  341. v = i.args[0]
  342. if v.is_number and (v < small) == True:
  343. small = v
  344. big = Max.identity
  345. for i in maxs:
  346. v = i.args[0]
  347. if v.is_number and (v > big) == True:
  348. big = v
  349. # at the point when this function is called from __new__,
  350. # there may be more than one numeric arg present since
  351. # local zeros have not been handled yet, so look through
  352. # more than the first arg
  353. if cls == Min:
  354. for i in range(len(args)):
  355. if not args[i].is_number:
  356. break
  357. if (args[i] < small) == True:
  358. small = args[i]
  359. elif cls == Max:
  360. for i in range(len(args)):
  361. if not args[i].is_number:
  362. break
  363. if (args[i] > big) == True:
  364. big = args[i]
  365. T = None
  366. if cls == Min:
  367. if small != Min.identity:
  368. other = Max
  369. T = small
  370. elif big != Max.identity:
  371. other = Min
  372. T = big
  373. if T is not None:
  374. # remove numerical redundancy
  375. for i in range(len(args)):
  376. a = args[i]
  377. if isinstance(a, other):
  378. a0 = a.args[0]
  379. if ((a0 > T) if other == Max else (a0 < T)) == True:
  380. args[i] = cls.identity
  381. # remove redundant symbolic args
  382. def do(ai, a):
  383. if not isinstance(ai, (Min, Max)):
  384. return ai
  385. cond = a in ai.args
  386. if not cond:
  387. return ai.func(*[do(i, a) for i in ai.args],
  388. evaluate=False)
  389. if isinstance(ai, cls):
  390. return ai.func(*[do(i, a) for i in ai.args if i != a],
  391. evaluate=False)
  392. return a
  393. for i, a in enumerate(args):
  394. args[i + 1:] = [do(ai, a) for ai in args[i + 1:]]
  395. # factor out common elements as for
  396. # Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z))
  397. # and vice versa when swapping Min/Max -- do this only for the
  398. # easy case where all functions contain something in common;
  399. # trying to find some optimal subset of args to modify takes
  400. # too long
  401. def factor_minmax(args):
  402. is_other = lambda arg: isinstance(arg, other)
  403. other_args, remaining_args = sift(args, is_other, binary=True)
  404. if not other_args:
  405. return args
  406. # Min(Max(x, y, z), Max(x, y, u, v)) -> {x,y}, ({z}, {u,v})
  407. arg_sets = [set(arg.args) for arg in other_args]
  408. common = set.intersection(*arg_sets)
  409. if not common:
  410. return args
  411. new_other_args = list(common)
  412. arg_sets_diff = [arg_set - common for arg_set in arg_sets]
  413. # If any set is empty after removing common then all can be
  414. # discarded e.g. Min(Max(a, b, c), Max(a, b)) -> Max(a, b)
  415. if all(arg_sets_diff):
  416. other_args_diff = [other(*s, evaluate=False) for s in arg_sets_diff]
  417. new_other_args.append(cls(*other_args_diff, evaluate=False))
  418. other_args_factored = other(*new_other_args, evaluate=False)
  419. return remaining_args + [other_args_factored]
  420. if len(args) > 1:
  421. args = factor_minmax(args)
  422. return args
  423. @classmethod
  424. def _new_args_filter(cls, arg_sequence):
  425. """
  426. Generator filtering args.
  427. first standard filter, for cls.zero and cls.identity.
  428. Also reshape ``Max(a, Max(b, c))`` to ``Max(a, b, c)``,
  429. and check arguments for comparability
  430. """
  431. for arg in arg_sequence:
  432. # pre-filter, checking comparability of arguments
  433. if not isinstance(arg, Expr) or arg.is_extended_real is False or (
  434. arg.is_number and
  435. not arg.is_comparable):
  436. raise ValueError("The argument '%s' is not comparable." % arg)
  437. if arg == cls.zero:
  438. raise ShortCircuit(arg)
  439. elif arg == cls.identity:
  440. continue
  441. elif arg.func == cls:
  442. yield from arg.args
  443. else:
  444. yield arg
  445. @classmethod
  446. def _find_localzeros(cls, values, **options):
  447. """
  448. Sequentially allocate values to localzeros.
  449. When a value is identified as being more extreme than another member it
  450. replaces that member; if this is never true, then the value is simply
  451. appended to the localzeros.
  452. """
  453. localzeros = set()
  454. for v in values:
  455. is_newzero = True
  456. localzeros_ = list(localzeros)
  457. for z in localzeros_:
  458. if id(v) == id(z):
  459. is_newzero = False
  460. else:
  461. con = cls._is_connected(v, z)
  462. if con:
  463. is_newzero = False
  464. if con is True or con == cls:
  465. localzeros.remove(z)
  466. localzeros.update([v])
  467. if is_newzero:
  468. localzeros.update([v])
  469. return localzeros
  470. @classmethod
  471. def _is_connected(cls, x, y):
  472. """
  473. Check if x and y are connected somehow.
  474. """
  475. for i in range(2):
  476. if x == y:
  477. return True
  478. t, f = Max, Min
  479. for op in "><":
  480. for j in range(2):
  481. try:
  482. if op == ">":
  483. v = x >= y
  484. else:
  485. v = x <= y
  486. except TypeError:
  487. return False # non-real arg
  488. if not v.is_Relational:
  489. return t if v else f
  490. t, f = f, t
  491. x, y = y, x
  492. x, y = y, x # run next pass with reversed order relative to start
  493. # simplification can be expensive, so be conservative
  494. # in what is attempted
  495. x = factor_terms(x - y)
  496. y = S.Zero
  497. return False
  498. def _eval_derivative(self, s):
  499. # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
  500. i = 0
  501. l = []
  502. for a in self.args:
  503. i += 1
  504. da = a.diff(s)
  505. if da.is_zero:
  506. continue
  507. try:
  508. df = self.fdiff(i)
  509. except ArgumentIndexError:
  510. df = Function.fdiff(self, i)
  511. l.append(df * da)
  512. return Add(*l)
  513. def _eval_rewrite_as_Abs(self, *args, **kwargs):
  514. from sympy.functions.elementary.complexes import Abs
  515. s = (args[0] + self.func(*args[1:]))/2
  516. d = abs(args[0] - self.func(*args[1:]))/2
  517. return (s + d if isinstance(self, Max) else s - d).rewrite(Abs)
  518. def evalf(self, n=15, **options):
  519. return self.func(*[a.evalf(n, **options) for a in self.args])
  520. def n(self, *args, **kwargs):
  521. return self.evalf(*args, **kwargs)
  522. _eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args)
  523. _eval_is_antihermitian = lambda s: _torf(i.is_antihermitian for i in s.args)
  524. _eval_is_commutative = lambda s: _torf(i.is_commutative for i in s.args)
  525. _eval_is_complex = lambda s: _torf(i.is_complex for i in s.args)
  526. _eval_is_composite = lambda s: _torf(i.is_composite for i in s.args)
  527. _eval_is_even = lambda s: _torf(i.is_even for i in s.args)
  528. _eval_is_finite = lambda s: _torf(i.is_finite for i in s.args)
  529. _eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args)
  530. _eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args)
  531. _eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args)
  532. _eval_is_integer = lambda s: _torf(i.is_integer for i in s.args)
  533. _eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args)
  534. _eval_is_negative = lambda s: _torf(i.is_negative for i in s.args)
  535. _eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args)
  536. _eval_is_nonnegative = lambda s: _torf(i.is_nonnegative for i in s.args)
  537. _eval_is_nonpositive = lambda s: _torf(i.is_nonpositive for i in s.args)
  538. _eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args)
  539. _eval_is_odd = lambda s: _torf(i.is_odd for i in s.args)
  540. _eval_is_polar = lambda s: _torf(i.is_polar for i in s.args)
  541. _eval_is_positive = lambda s: _torf(i.is_positive for i in s.args)
  542. _eval_is_prime = lambda s: _torf(i.is_prime for i in s.args)
  543. _eval_is_rational = lambda s: _torf(i.is_rational for i in s.args)
  544. _eval_is_real = lambda s: _torf(i.is_real for i in s.args)
  545. _eval_is_extended_real = lambda s: _torf(i.is_extended_real for i in s.args)
  546. _eval_is_transcendental = lambda s: _torf(i.is_transcendental for i in s.args)
  547. _eval_is_zero = lambda s: _torf(i.is_zero for i in s.args)
  548. class Max(MinMaxBase, Application):
  549. r"""
  550. Return, if possible, the maximum value of the list.
  551. When number of arguments is equal one, then
  552. return this argument.
  553. When number of arguments is equal two, then
  554. return, if possible, the value from (a, b) that is $\ge$ the other.
  555. In common case, when the length of list greater than 2, the task
  556. is more complicated. Return only the arguments, which are greater
  557. than others, if it is possible to determine directional relation.
  558. If is not possible to determine such a relation, return a partially
  559. evaluated result.
  560. Assumptions are used to make the decision too.
  561. Also, only comparable arguments are permitted.
  562. It is named ``Max`` and not ``max`` to avoid conflicts
  563. with the built-in function ``max``.
  564. Examples
  565. ========
  566. >>> from sympy import Max, Symbol, oo
  567. >>> from sympy.abc import x, y, z
  568. >>> p = Symbol('p', positive=True)
  569. >>> n = Symbol('n', negative=True)
  570. >>> Max(x, -2)
  571. Max(-2, x)
  572. >>> Max(x, -2).subs(x, 3)
  573. 3
  574. >>> Max(p, -2)
  575. p
  576. >>> Max(x, y)
  577. Max(x, y)
  578. >>> Max(x, y) == Max(y, x)
  579. True
  580. >>> Max(x, Max(y, z))
  581. Max(x, y, z)
  582. >>> Max(n, 8, p, 7, -oo)
  583. Max(8, p)
  584. >>> Max (1, x, oo)
  585. oo
  586. * Algorithm
  587. The task can be considered as searching of supremums in the
  588. directed complete partial orders [1]_.
  589. The source values are sequentially allocated by the isolated subsets
  590. in which supremums are searched and result as Max arguments.
  591. If the resulted supremum is single, then it is returned.
  592. The isolated subsets are the sets of values which are only the comparable
  593. with each other in the current set. E.g. natural numbers are comparable with
  594. each other, but not comparable with the `x` symbol. Another example: the
  595. symbol `x` with negative assumption is comparable with a natural number.
  596. Also there are "least" elements, which are comparable with all others,
  597. and have a zero property (maximum or minimum for all elements).
  598. For example, in case of $\infty$, the allocation operation is terminated
  599. and only this value is returned.
  600. Assumption:
  601. - if $A > B > C$ then $A > C$
  602. - if $A = B$ then $B$ can be removed
  603. References
  604. ==========
  605. .. [1] https://en.wikipedia.org/wiki/Directed_complete_partial_order
  606. .. [2] https://en.wikipedia.org/wiki/Lattice_%28order%29
  607. See Also
  608. ========
  609. Min : find minimum values
  610. """
  611. zero = S.Infinity
  612. identity = S.NegativeInfinity
  613. def fdiff( self, argindex ):
  614. from sympy.functions.special.delta_functions import Heaviside
  615. n = len(self.args)
  616. if 0 < argindex and argindex <= n:
  617. argindex -= 1
  618. if n == 2:
  619. return Heaviside(self.args[argindex] - self.args[1 - argindex])
  620. newargs = tuple([self.args[i] for i in range(n) if i != argindex])
  621. return Heaviside(self.args[argindex] - Max(*newargs))
  622. else:
  623. raise ArgumentIndexError(self, argindex)
  624. def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
  625. from sympy.functions.special.delta_functions import Heaviside
  626. return Add(*[j*Mul(*[Heaviside(j - i) for i in args if i!=j]) \
  627. for j in args])
  628. def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
  629. return _minmax_as_Piecewise('>=', *args)
  630. def _eval_is_positive(self):
  631. return fuzzy_or(a.is_positive for a in self.args)
  632. def _eval_is_nonnegative(self):
  633. return fuzzy_or(a.is_nonnegative for a in self.args)
  634. def _eval_is_negative(self):
  635. return fuzzy_and(a.is_negative for a in self.args)
  636. class Min(MinMaxBase, Application):
  637. """
  638. Return, if possible, the minimum value of the list.
  639. It is named ``Min`` and not ``min`` to avoid conflicts
  640. with the built-in function ``min``.
  641. Examples
  642. ========
  643. >>> from sympy import Min, Symbol, oo
  644. >>> from sympy.abc import x, y
  645. >>> p = Symbol('p', positive=True)
  646. >>> n = Symbol('n', negative=True)
  647. >>> Min(x, -2)
  648. Min(-2, x)
  649. >>> Min(x, -2).subs(x, 3)
  650. -2
  651. >>> Min(p, -3)
  652. -3
  653. >>> Min(x, y)
  654. Min(x, y)
  655. >>> Min(n, 8, p, -7, p, oo)
  656. Min(-7, n)
  657. See Also
  658. ========
  659. Max : find maximum values
  660. """
  661. zero = S.NegativeInfinity
  662. identity = S.Infinity
  663. def fdiff( self, argindex ):
  664. from sympy.functions.special.delta_functions import Heaviside
  665. n = len(self.args)
  666. if 0 < argindex and argindex <= n:
  667. argindex -= 1
  668. if n == 2:
  669. return Heaviside( self.args[1-argindex] - self.args[argindex] )
  670. newargs = tuple([ self.args[i] for i in range(n) if i != argindex])
  671. return Heaviside( Min(*newargs) - self.args[argindex] )
  672. else:
  673. raise ArgumentIndexError(self, argindex)
  674. def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
  675. from sympy.functions.special.delta_functions import Heaviside
  676. return Add(*[j*Mul(*[Heaviside(i-j) for i in args if i!=j]) \
  677. for j in args])
  678. def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
  679. return _minmax_as_Piecewise('<=', *args)
  680. def _eval_is_positive(self):
  681. return fuzzy_and(a.is_positive for a in self.args)
  682. def _eval_is_nonnegative(self):
  683. return fuzzy_and(a.is_nonnegative for a in self.args)
  684. def _eval_is_negative(self):
  685. return fuzzy_or(a.is_negative for a in self.args)
  686. class Rem(Function):
  687. """Returns the remainder when ``p`` is divided by ``q`` where ``p`` is finite
  688. and ``q`` is not equal to zero. The result, ``p - int(p/q)*q``, has the same sign
  689. as the divisor.
  690. Parameters
  691. ==========
  692. p : Expr
  693. Dividend.
  694. q : Expr
  695. Divisor.
  696. Notes
  697. =====
  698. ``Rem`` corresponds to the ``%`` operator in C.
  699. Examples
  700. ========
  701. >>> from sympy.abc import x, y
  702. >>> from sympy import Rem
  703. >>> Rem(x**3, y)
  704. Rem(x**3, y)
  705. >>> Rem(x**3, y).subs({x: -5, y: 3})
  706. -2
  707. See Also
  708. ========
  709. Mod
  710. """
  711. kind = NumberKind
  712. @classmethod
  713. def eval(cls, p, q):
  714. def doit(p, q):
  715. """ the function remainder if both p,q are numbers
  716. and q is not zero
  717. """
  718. if q.is_zero:
  719. raise ZeroDivisionError("Division by zero")
  720. if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False:
  721. return S.NaN
  722. if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1):
  723. return S.Zero
  724. if q.is_Number:
  725. if p.is_Number:
  726. return p - Integer(p/q)*q
  727. rv = doit(p, q)
  728. if rv is not None:
  729. return rv