miscellaneous.py 27 KB

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