inequalities.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. """Tools for solving inequalities and systems of inequalities. """
  2. import itertools
  3. from sympy.calculus.util import (continuous_domain, periodicity,
  4. function_range)
  5. from sympy.core import sympify
  6. from sympy.core.exprtools import factor_terms
  7. from sympy.core.relational import Relational, Lt, Ge, Eq
  8. from sympy.core.symbol import Symbol, Dummy
  9. from sympy.sets.sets import Interval, FiniteSet, Union, Intersection
  10. from sympy.core.singleton import S
  11. from sympy.core.function import expand_mul
  12. from sympy.functions.elementary.complexes import Abs
  13. from sympy.logic import And
  14. from sympy.polys import Poly, PolynomialError, parallel_poly_from_expr
  15. from sympy.polys.polyutils import _nsort
  16. from sympy.solvers.solveset import solvify, solveset
  17. from sympy.utilities.iterables import sift, iterable
  18. from sympy.utilities.misc import filldedent
  19. def solve_poly_inequality(poly, rel):
  20. """Solve a polynomial inequality with rational coefficients.
  21. Examples
  22. ========
  23. >>> from sympy import solve_poly_inequality, Poly
  24. >>> from sympy.abc import x
  25. >>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==')
  26. [{0}]
  27. >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=')
  28. [Interval.open(-oo, -1), Interval.open(-1, 1), Interval.open(1, oo)]
  29. >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==')
  30. [{-1}, {1}]
  31. See Also
  32. ========
  33. solve_poly_inequalities
  34. """
  35. if not isinstance(poly, Poly):
  36. raise ValueError(
  37. 'For efficiency reasons, `poly` should be a Poly instance')
  38. if poly.as_expr().is_number:
  39. t = Relational(poly.as_expr(), 0, rel)
  40. if t is S.true:
  41. return [S.Reals]
  42. elif t is S.false:
  43. return [S.EmptySet]
  44. else:
  45. raise NotImplementedError(
  46. "could not determine truth value of %s" % t)
  47. reals, intervals = poly.real_roots(multiple=False), []
  48. if rel == '==':
  49. for root, _ in reals:
  50. interval = Interval(root, root)
  51. intervals.append(interval)
  52. elif rel == '!=':
  53. left = S.NegativeInfinity
  54. for right, _ in reals + [(S.Infinity, 1)]:
  55. interval = Interval(left, right, True, True)
  56. intervals.append(interval)
  57. left = right
  58. else:
  59. if poly.LC() > 0:
  60. sign = +1
  61. else:
  62. sign = -1
  63. eq_sign, equal = None, False
  64. if rel == '>':
  65. eq_sign = +1
  66. elif rel == '<':
  67. eq_sign = -1
  68. elif rel == '>=':
  69. eq_sign, equal = +1, True
  70. elif rel == '<=':
  71. eq_sign, equal = -1, True
  72. else:
  73. raise ValueError("'%s' is not a valid relation" % rel)
  74. right, right_open = S.Infinity, True
  75. for left, multiplicity in reversed(reals):
  76. if multiplicity % 2:
  77. if sign == eq_sign:
  78. intervals.insert(
  79. 0, Interval(left, right, not equal, right_open))
  80. sign, right, right_open = -sign, left, not equal
  81. else:
  82. if sign == eq_sign and not equal:
  83. intervals.insert(
  84. 0, Interval(left, right, True, right_open))
  85. right, right_open = left, True
  86. elif sign != eq_sign and equal:
  87. intervals.insert(0, Interval(left, left))
  88. if sign == eq_sign:
  89. intervals.insert(
  90. 0, Interval(S.NegativeInfinity, right, True, right_open))
  91. return intervals
  92. def solve_poly_inequalities(polys):
  93. """Solve polynomial inequalities with rational coefficients.
  94. Examples
  95. ========
  96. >>> from sympy import Poly
  97. >>> from sympy.solvers.inequalities import solve_poly_inequalities
  98. >>> from sympy.abc import x
  99. >>> solve_poly_inequalities(((
  100. ... Poly(x**2 - 3), ">"), (
  101. ... Poly(-x**2 + 1), ">")))
  102. Union(Interval.open(-oo, -sqrt(3)), Interval.open(-1, 1), Interval.open(sqrt(3), oo))
  103. """
  104. return Union(*[s for p in polys for s in solve_poly_inequality(*p)])
  105. def solve_rational_inequalities(eqs):
  106. """Solve a system of rational inequalities with rational coefficients.
  107. Examples
  108. ========
  109. >>> from sympy.abc import x
  110. >>> from sympy import solve_rational_inequalities, Poly
  111. >>> solve_rational_inequalities([[
  112. ... ((Poly(-x + 1), Poly(1, x)), '>='),
  113. ... ((Poly(-x + 1), Poly(1, x)), '<=')]])
  114. {1}
  115. >>> solve_rational_inequalities([[
  116. ... ((Poly(x), Poly(1, x)), '!='),
  117. ... ((Poly(-x + 1), Poly(1, x)), '>=')]])
  118. Union(Interval.open(-oo, 0), Interval.Lopen(0, 1))
  119. See Also
  120. ========
  121. solve_poly_inequality
  122. """
  123. result = S.EmptySet
  124. for _eqs in eqs:
  125. if not _eqs:
  126. continue
  127. global_intervals = [Interval(S.NegativeInfinity, S.Infinity)]
  128. for (numer, denom), rel in _eqs:
  129. numer_intervals = solve_poly_inequality(numer*denom, rel)
  130. denom_intervals = solve_poly_inequality(denom, '==')
  131. intervals = []
  132. for numer_interval, global_interval in itertools.product(
  133. numer_intervals, global_intervals):
  134. interval = numer_interval.intersect(global_interval)
  135. if interval is not S.EmptySet:
  136. intervals.append(interval)
  137. global_intervals = intervals
  138. intervals = []
  139. for global_interval in global_intervals:
  140. for denom_interval in denom_intervals:
  141. global_interval -= denom_interval
  142. if global_interval is not S.EmptySet:
  143. intervals.append(global_interval)
  144. global_intervals = intervals
  145. if not global_intervals:
  146. break
  147. for interval in global_intervals:
  148. result = result.union(interval)
  149. return result
  150. def reduce_rational_inequalities(exprs, gen, relational=True):
  151. """Reduce a system of rational inequalities with rational coefficients.
  152. Examples
  153. ========
  154. >>> from sympy import Symbol
  155. >>> from sympy.solvers.inequalities import reduce_rational_inequalities
  156. >>> x = Symbol('x', real=True)
  157. >>> reduce_rational_inequalities([[x**2 <= 0]], x)
  158. Eq(x, 0)
  159. >>> reduce_rational_inequalities([[x + 2 > 0]], x)
  160. -2 < x
  161. >>> reduce_rational_inequalities([[(x + 2, ">")]], x)
  162. -2 < x
  163. >>> reduce_rational_inequalities([[x + 2]], x)
  164. Eq(x, -2)
  165. This function find the non-infinite solution set so if the unknown symbol
  166. is declared as extended real rather than real then the result may include
  167. finiteness conditions:
  168. >>> y = Symbol('y', extended_real=True)
  169. >>> reduce_rational_inequalities([[y + 2 > 0]], y)
  170. (-2 < y) & (y < oo)
  171. """
  172. exact = True
  173. eqs = []
  174. solution = S.EmptySet # add pieces for each group
  175. for _exprs in exprs:
  176. if not _exprs:
  177. continue
  178. _eqs = []
  179. _sol = S.Reals
  180. for expr in _exprs:
  181. if isinstance(expr, tuple):
  182. expr, rel = expr
  183. else:
  184. if expr.is_Relational:
  185. expr, rel = expr.lhs - expr.rhs, expr.rel_op
  186. else:
  187. rel = '=='
  188. if expr is S.true:
  189. numer, denom, rel = S.Zero, S.One, '=='
  190. elif expr is S.false:
  191. numer, denom, rel = S.One, S.One, '=='
  192. else:
  193. numer, denom = expr.together().as_numer_denom()
  194. try:
  195. (numer, denom), opt = parallel_poly_from_expr(
  196. (numer, denom), gen)
  197. except PolynomialError:
  198. raise PolynomialError(filldedent('''
  199. only polynomials and rational functions are
  200. supported in this context.
  201. '''))
  202. if not opt.domain.is_Exact:
  203. numer, denom, exact = numer.to_exact(), denom.to_exact(), False
  204. domain = opt.domain.get_exact()
  205. if not (domain.is_ZZ or domain.is_QQ):
  206. expr = numer/denom
  207. expr = Relational(expr, 0, rel)
  208. _sol &= solve_univariate_inequality(expr, gen, relational=False)
  209. else:
  210. _eqs.append(((numer, denom), rel))
  211. if _eqs:
  212. _sol &= solve_rational_inequalities([_eqs])
  213. exclude = solve_rational_inequalities([[((d, d.one), '==')
  214. for i in eqs for ((n, d), _) in i if d.has(gen)]])
  215. _sol -= exclude
  216. solution |= _sol
  217. if not exact and solution:
  218. solution = solution.evalf()
  219. if relational:
  220. solution = solution.as_relational(gen)
  221. return solution
  222. def reduce_abs_inequality(expr, rel, gen):
  223. """Reduce an inequality with nested absolute values.
  224. Examples
  225. ========
  226. >>> from sympy import reduce_abs_inequality, Abs, Symbol
  227. >>> x = Symbol('x', real=True)
  228. >>> reduce_abs_inequality(Abs(x - 5) - 3, '<', x)
  229. (2 < x) & (x < 8)
  230. >>> reduce_abs_inequality(Abs(x + 2)*3 - 13, '<', x)
  231. (-19/3 < x) & (x < 7/3)
  232. See Also
  233. ========
  234. reduce_abs_inequalities
  235. """
  236. if gen.is_extended_real is False:
  237. raise TypeError(filldedent('''
  238. Cannot solve inequalities with absolute values containing
  239. non-real variables.
  240. '''))
  241. def _bottom_up_scan(expr):
  242. exprs = []
  243. if expr.is_Add or expr.is_Mul:
  244. op = expr.func
  245. for arg in expr.args:
  246. _exprs = _bottom_up_scan(arg)
  247. if not exprs:
  248. exprs = _exprs
  249. else:
  250. exprs = [(op(expr, _expr), conds + _conds) for (expr, conds), (_expr, _conds) in
  251. itertools.product(exprs, _exprs)]
  252. elif expr.is_Pow:
  253. n = expr.exp
  254. if not n.is_Integer:
  255. raise ValueError("Only Integer Powers are allowed on Abs.")
  256. exprs.extend((expr**n, conds) for expr, conds in _bottom_up_scan(expr.base))
  257. elif isinstance(expr, Abs):
  258. _exprs = _bottom_up_scan(expr.args[0])
  259. for expr, conds in _exprs:
  260. exprs.append(( expr, conds + [Ge(expr, 0)]))
  261. exprs.append((-expr, conds + [Lt(expr, 0)]))
  262. else:
  263. exprs = [(expr, [])]
  264. return exprs
  265. mapping = {'<': '>', '<=': '>='}
  266. inequalities = []
  267. for expr, conds in _bottom_up_scan(expr):
  268. if rel not in mapping.keys():
  269. expr = Relational( expr, 0, rel)
  270. else:
  271. expr = Relational(-expr, 0, mapping[rel])
  272. inequalities.append([expr] + conds)
  273. return reduce_rational_inequalities(inequalities, gen)
  274. def reduce_abs_inequalities(exprs, gen):
  275. """Reduce a system of inequalities with nested absolute values.
  276. Examples
  277. ========
  278. >>> from sympy import reduce_abs_inequalities, Abs, Symbol
  279. >>> x = Symbol('x', extended_real=True)
  280. >>> reduce_abs_inequalities([(Abs(3*x - 5) - 7, '<'),
  281. ... (Abs(x + 25) - 13, '>')], x)
  282. (-2/3 < x) & (x < 4) & (((-oo < x) & (x < -38)) | ((-12 < x) & (x < oo)))
  283. >>> reduce_abs_inequalities([(Abs(x - 4) + Abs(3*x - 5) - 7, '<')], x)
  284. (1/2 < x) & (x < 4)
  285. See Also
  286. ========
  287. reduce_abs_inequality
  288. """
  289. return And(*[ reduce_abs_inequality(expr, rel, gen)
  290. for expr, rel in exprs ])
  291. def solve_univariate_inequality(expr, gen, relational=True, domain=S.Reals, continuous=False):
  292. """Solves a real univariate inequality.
  293. Parameters
  294. ==========
  295. expr : Relational
  296. The target inequality
  297. gen : Symbol
  298. The variable for which the inequality is solved
  299. relational : bool
  300. A Relational type output is expected or not
  301. domain : Set
  302. The domain over which the equation is solved
  303. continuous: bool
  304. True if expr is known to be continuous over the given domain
  305. (and so continuous_domain() does not need to be called on it)
  306. Raises
  307. ======
  308. NotImplementedError
  309. The solution of the inequality cannot be determined due to limitation
  310. in :func:`sympy.solvers.solveset.solvify`.
  311. Notes
  312. =====
  313. Currently, we cannot solve all the inequalities due to limitations in
  314. :func:`sympy.solvers.solveset.solvify`. Also, the solution returned for trigonometric inequalities
  315. are restricted in its periodic interval.
  316. See Also
  317. ========
  318. sympy.solvers.solveset.solvify: solver returning solveset solutions with solve's output API
  319. Examples
  320. ========
  321. >>> from sympy import solve_univariate_inequality, Symbol, sin, Interval, S
  322. >>> x = Symbol('x')
  323. >>> solve_univariate_inequality(x**2 >= 4, x)
  324. ((2 <= x) & (x < oo)) | ((-oo < x) & (x <= -2))
  325. >>> solve_univariate_inequality(x**2 >= 4, x, relational=False)
  326. Union(Interval(-oo, -2), Interval(2, oo))
  327. >>> domain = Interval(0, S.Infinity)
  328. >>> solve_univariate_inequality(x**2 >= 4, x, False, domain)
  329. Interval(2, oo)
  330. >>> solve_univariate_inequality(sin(x) > 0, x, relational=False)
  331. Interval.open(0, pi)
  332. """
  333. from sympy.solvers.solvers import denoms
  334. if domain.is_subset(S.Reals) is False:
  335. raise NotImplementedError(filldedent('''
  336. Inequalities in the complex domain are
  337. not supported. Try the real domain by
  338. setting domain=S.Reals'''))
  339. elif domain is not S.Reals:
  340. rv = solve_univariate_inequality(
  341. expr, gen, relational=False, continuous=continuous).intersection(domain)
  342. if relational:
  343. rv = rv.as_relational(gen)
  344. return rv
  345. else:
  346. pass # continue with attempt to solve in Real domain
  347. # This keeps the function independent of the assumptions about `gen`.
  348. # `solveset` makes sure this function is called only when the domain is
  349. # real.
  350. _gen = gen
  351. _domain = domain
  352. if gen.is_extended_real is False:
  353. rv = S.EmptySet
  354. return rv if not relational else rv.as_relational(_gen)
  355. elif gen.is_extended_real is None:
  356. gen = Dummy('gen', extended_real=True)
  357. try:
  358. expr = expr.xreplace({_gen: gen})
  359. except TypeError:
  360. raise TypeError(filldedent('''
  361. When gen is real, the relational has a complex part
  362. which leads to an invalid comparison like I < 0.
  363. '''))
  364. rv = None
  365. if expr is S.true:
  366. rv = domain
  367. elif expr is S.false:
  368. rv = S.EmptySet
  369. else:
  370. e = expr.lhs - expr.rhs
  371. period = periodicity(e, gen)
  372. if period == S.Zero:
  373. e = expand_mul(e)
  374. const = expr.func(e, 0)
  375. if const is S.true:
  376. rv = domain
  377. elif const is S.false:
  378. rv = S.EmptySet
  379. elif period is not None:
  380. frange = function_range(e, gen, domain)
  381. rel = expr.rel_op
  382. if rel in ('<', '<='):
  383. if expr.func(frange.sup, 0):
  384. rv = domain
  385. elif not expr.func(frange.inf, 0):
  386. rv = S.EmptySet
  387. elif rel in ('>', '>='):
  388. if expr.func(frange.inf, 0):
  389. rv = domain
  390. elif not expr.func(frange.sup, 0):
  391. rv = S.EmptySet
  392. inf, sup = domain.inf, domain.sup
  393. if sup - inf is S.Infinity:
  394. domain = Interval(0, period, False, True).intersect(_domain)
  395. _domain = domain
  396. if rv is None:
  397. n, d = e.as_numer_denom()
  398. try:
  399. if gen not in n.free_symbols and len(e.free_symbols) > 1:
  400. raise ValueError
  401. # this might raise ValueError on its own
  402. # or it might give None...
  403. solns = solvify(e, gen, domain)
  404. if solns is None:
  405. # in which case we raise ValueError
  406. raise ValueError
  407. except (ValueError, NotImplementedError):
  408. # replace gen with generic x since it's
  409. # univariate anyway
  410. raise NotImplementedError(filldedent('''
  411. The inequality, %s, cannot be solved using
  412. solve_univariate_inequality.
  413. ''' % expr.subs(gen, Symbol('x'))))
  414. expanded_e = expand_mul(e)
  415. def valid(x):
  416. # this is used to see if gen=x satisfies the
  417. # relational by substituting it into the
  418. # expanded form and testing against 0, e.g.
  419. # if expr = x*(x + 1) < 2 then e = x*(x + 1) - 2
  420. # and expanded_e = x**2 + x - 2; the test is
  421. # whether a given value of x satisfies
  422. # x**2 + x - 2 < 0
  423. #
  424. # expanded_e, expr and gen used from enclosing scope
  425. v = expanded_e.subs(gen, expand_mul(x))
  426. try:
  427. r = expr.func(v, 0)
  428. except TypeError:
  429. r = S.false
  430. if r in (S.true, S.false):
  431. return r
  432. if v.is_extended_real is False:
  433. return S.false
  434. else:
  435. v = v.n(2)
  436. if v.is_comparable:
  437. return expr.func(v, 0)
  438. # not comparable or couldn't be evaluated
  439. raise NotImplementedError(
  440. 'relationship did not evaluate: %s' % r)
  441. singularities = []
  442. for d in denoms(expr, gen):
  443. singularities.extend(solvify(d, gen, domain))
  444. if not continuous:
  445. domain = continuous_domain(expanded_e, gen, domain)
  446. include_x = '=' in expr.rel_op and expr.rel_op != '!='
  447. try:
  448. discontinuities = set(domain.boundary -
  449. FiniteSet(domain.inf, domain.sup))
  450. # remove points that are not between inf and sup of domain
  451. critical_points = FiniteSet(*(solns + singularities + list(
  452. discontinuities))).intersection(
  453. Interval(domain.inf, domain.sup,
  454. domain.inf not in domain, domain.sup not in domain))
  455. if all(r.is_number for r in critical_points):
  456. reals = _nsort(critical_points, separated=True)[0]
  457. else:
  458. sifted = sift(critical_points, lambda x: x.is_extended_real)
  459. if sifted[None]:
  460. # there were some roots that weren't known
  461. # to be real
  462. raise NotImplementedError
  463. try:
  464. reals = sifted[True]
  465. if len(reals) > 1:
  466. reals = sorted(reals)
  467. except TypeError:
  468. raise NotImplementedError
  469. except NotImplementedError:
  470. raise NotImplementedError('sorting of these roots is not supported')
  471. # If expr contains imaginary coefficients, only take real
  472. # values of x for which the imaginary part is 0
  473. make_real = S.Reals
  474. if (coeffI := expanded_e.coeff(S.ImaginaryUnit)) != S.Zero:
  475. check = True
  476. im_sol = FiniteSet()
  477. try:
  478. a = solveset(coeffI, gen, domain)
  479. if not isinstance(a, Interval):
  480. for z in a:
  481. if z not in singularities and valid(z) and z.is_extended_real:
  482. im_sol += FiniteSet(z)
  483. else:
  484. start, end = a.inf, a.sup
  485. for z in _nsort(critical_points + FiniteSet(end)):
  486. valid_start = valid(start)
  487. if start != end:
  488. valid_z = valid(z)
  489. pt = _pt(start, z)
  490. if pt not in singularities and pt.is_extended_real and valid(pt):
  491. if valid_start and valid_z:
  492. im_sol += Interval(start, z)
  493. elif valid_start:
  494. im_sol += Interval.Ropen(start, z)
  495. elif valid_z:
  496. im_sol += Interval.Lopen(start, z)
  497. else:
  498. im_sol += Interval.open(start, z)
  499. start = z
  500. for s in singularities:
  501. im_sol -= FiniteSet(s)
  502. except (TypeError):
  503. im_sol = S.Reals
  504. check = False
  505. if im_sol is S.EmptySet:
  506. raise ValueError(filldedent('''
  507. %s contains imaginary parts which cannot be
  508. made 0 for any value of %s satisfying the
  509. inequality, leading to relations like I < 0.
  510. ''' % (expr.subs(gen, _gen), _gen)))
  511. make_real = make_real.intersect(im_sol)
  512. sol_sets = [S.EmptySet]
  513. start = domain.inf
  514. if start in domain and valid(start) and start.is_finite:
  515. sol_sets.append(FiniteSet(start))
  516. for x in reals:
  517. end = x
  518. if valid(_pt(start, end)):
  519. sol_sets.append(Interval(start, end, True, True))
  520. if x in singularities:
  521. singularities.remove(x)
  522. else:
  523. if x in discontinuities:
  524. discontinuities.remove(x)
  525. _valid = valid(x)
  526. else: # it's a solution
  527. _valid = include_x
  528. if _valid:
  529. sol_sets.append(FiniteSet(x))
  530. start = end
  531. end = domain.sup
  532. if end in domain and valid(end) and end.is_finite:
  533. sol_sets.append(FiniteSet(end))
  534. if valid(_pt(start, end)):
  535. sol_sets.append(Interval.open(start, end))
  536. if coeffI != S.Zero and check:
  537. rv = (make_real).intersect(_domain)
  538. else:
  539. rv = Intersection(
  540. (Union(*sol_sets)), make_real, _domain).subs(gen, _gen)
  541. return rv if not relational else rv.as_relational(_gen)
  542. def _pt(start, end):
  543. """Return a point between start and end"""
  544. if not start.is_infinite and not end.is_infinite:
  545. pt = (start + end)/2
  546. elif start.is_infinite and end.is_infinite:
  547. pt = S.Zero
  548. else:
  549. if (start.is_infinite and start.is_extended_positive is None or
  550. end.is_infinite and end.is_extended_positive is None):
  551. raise ValueError('cannot proceed with unsigned infinite values')
  552. if (end.is_infinite and end.is_extended_negative or
  553. start.is_infinite and start.is_extended_positive):
  554. start, end = end, start
  555. # if possible, use a multiple of self which has
  556. # better behavior when checking assumptions than
  557. # an expression obtained by adding or subtracting 1
  558. if end.is_infinite:
  559. if start.is_extended_positive:
  560. pt = start*2
  561. elif start.is_extended_negative:
  562. pt = start*S.Half
  563. else:
  564. pt = start + 1
  565. elif start.is_infinite:
  566. if end.is_extended_positive:
  567. pt = end*S.Half
  568. elif end.is_extended_negative:
  569. pt = end*2
  570. else:
  571. pt = end - 1
  572. return pt
  573. def _solve_inequality(ie, s, linear=False):
  574. """Return the inequality with s isolated on the left, if possible.
  575. If the relationship is non-linear, a solution involving And or Or
  576. may be returned. False or True are returned if the relationship
  577. is never True or always True, respectively.
  578. If `linear` is True (default is False) an `s`-dependent expression
  579. will be isolated on the left, if possible
  580. but it will not be solved for `s` unless the expression is linear
  581. in `s`. Furthermore, only "safe" operations which do not change the
  582. sense of the relationship are applied: no division by an unsigned
  583. value is attempted unless the relationship involves Eq or Ne and
  584. no division by a value not known to be nonzero is ever attempted.
  585. Examples
  586. ========
  587. >>> from sympy import Eq, Symbol
  588. >>> from sympy.solvers.inequalities import _solve_inequality as f
  589. >>> from sympy.abc import x, y
  590. For linear expressions, the symbol can be isolated:
  591. >>> f(x - 2 < 0, x)
  592. x < 2
  593. >>> f(-x - 6 < x, x)
  594. x > -3
  595. Sometimes nonlinear relationships will be False
  596. >>> f(x**2 + 4 < 0, x)
  597. False
  598. Or they may involve more than one region of values:
  599. >>> f(x**2 - 4 < 0, x)
  600. (-2 < x) & (x < 2)
  601. To restrict the solution to a relational, set linear=True
  602. and only the x-dependent portion will be isolated on the left:
  603. >>> f(x**2 - 4 < 0, x, linear=True)
  604. x**2 < 4
  605. Division of only nonzero quantities is allowed, so x cannot
  606. be isolated by dividing by y:
  607. >>> y.is_nonzero is None # it is unknown whether it is 0 or not
  608. True
  609. >>> f(x*y < 1, x)
  610. x*y < 1
  611. And while an equality (or inequality) still holds after dividing by a
  612. non-zero quantity
  613. >>> nz = Symbol('nz', nonzero=True)
  614. >>> f(Eq(x*nz, 1), x)
  615. Eq(x, 1/nz)
  616. the sign must be known for other inequalities involving > or <:
  617. >>> f(x*nz <= 1, x)
  618. nz*x <= 1
  619. >>> p = Symbol('p', positive=True)
  620. >>> f(x*p <= 1, x)
  621. x <= 1/p
  622. When there are denominators in the original expression that
  623. are removed by expansion, conditions for them will be returned
  624. as part of the result:
  625. >>> f(x < x*(2/x - 1), x)
  626. (x < 1) & Ne(x, 0)
  627. """
  628. from sympy.solvers.solvers import denoms
  629. if s not in ie.free_symbols:
  630. return ie
  631. if ie.rhs == s:
  632. ie = ie.reversed
  633. if ie.lhs == s and s not in ie.rhs.free_symbols:
  634. return ie
  635. def classify(ie, s, i):
  636. # return True or False if ie evaluates when substituting s with
  637. # i else None (if unevaluated) or NaN (when there is an error
  638. # in evaluating)
  639. try:
  640. v = ie.subs(s, i)
  641. if v is S.NaN:
  642. return v
  643. elif v not in (True, False):
  644. return
  645. return v
  646. except TypeError:
  647. return S.NaN
  648. rv = None
  649. oo = S.Infinity
  650. expr = ie.lhs - ie.rhs
  651. try:
  652. p = Poly(expr, s)
  653. if p.degree() == 0:
  654. rv = ie.func(p.as_expr(), 0)
  655. elif not linear and p.degree() > 1:
  656. # handle in except clause
  657. raise NotImplementedError
  658. except (PolynomialError, NotImplementedError):
  659. if not linear:
  660. try:
  661. rv = reduce_rational_inequalities([[ie]], s)
  662. except PolynomialError:
  663. rv = solve_univariate_inequality(ie, s)
  664. # remove restrictions wrt +/-oo that may have been
  665. # applied when using sets to simplify the relationship
  666. okoo = classify(ie, s, oo)
  667. if okoo is S.true and classify(rv, s, oo) is S.false:
  668. rv = rv.subs(s < oo, True)
  669. oknoo = classify(ie, s, -oo)
  670. if (oknoo is S.true and
  671. classify(rv, s, -oo) is S.false):
  672. rv = rv.subs(-oo < s, True)
  673. rv = rv.subs(s > -oo, True)
  674. if rv is S.true:
  675. rv = (s <= oo) if okoo is S.true else (s < oo)
  676. if oknoo is not S.true:
  677. rv = And(-oo < s, rv)
  678. else:
  679. p = Poly(expr)
  680. conds = []
  681. if rv is None:
  682. e = p.as_expr() # this is in expanded form
  683. # Do a safe inversion of e, moving non-s terms
  684. # to the rhs and dividing by a nonzero factor if
  685. # the relational is Eq/Ne; for other relationals
  686. # the sign must also be positive or negative
  687. rhs = 0
  688. b, ax = e.as_independent(s, as_Add=True)
  689. e -= b
  690. rhs -= b
  691. ef = factor_terms(e)
  692. a, e = ef.as_independent(s, as_Add=False)
  693. if (a.is_zero != False or # don't divide by potential 0
  694. a.is_negative ==
  695. a.is_positive is None and # if sign is not known then
  696. ie.rel_op not in ('!=', '==')): # reject if not Eq/Ne
  697. e = ef
  698. a = S.One
  699. rhs /= a
  700. if a.is_positive:
  701. rv = ie.func(e, rhs)
  702. else:
  703. rv = ie.reversed.func(e, rhs)
  704. # return conditions under which the value is
  705. # valid, too.
  706. beginning_denoms = denoms(ie.lhs) | denoms(ie.rhs)
  707. current_denoms = denoms(rv)
  708. for d in beginning_denoms - current_denoms:
  709. c = _solve_inequality(Eq(d, 0), s, linear=linear)
  710. if isinstance(c, Eq) and c.lhs == s:
  711. if classify(rv, s, c.rhs) is S.true:
  712. # rv is permitting this value but it shouldn't
  713. conds.append(~c)
  714. for i in (-oo, oo):
  715. if (classify(rv, s, i) is S.true and
  716. classify(ie, s, i) is not S.true):
  717. conds.append(s < i if i is oo else i < s)
  718. conds.append(rv)
  719. return And(*conds)
  720. def _reduce_inequalities(inequalities, symbols):
  721. # helper for reduce_inequalities
  722. poly_part, abs_part = {}, {}
  723. other = []
  724. for inequality in inequalities:
  725. expr, rel = inequality.lhs, inequality.rel_op # rhs is 0
  726. # check for gens using atoms which is more strict than free_symbols to
  727. # guard against EX domain which won't be handled by
  728. # reduce_rational_inequalities
  729. gens = expr.atoms(Symbol)
  730. if len(gens) == 1:
  731. gen = gens.pop()
  732. else:
  733. common = expr.free_symbols & symbols
  734. if len(common) == 1:
  735. gen = common.pop()
  736. other.append(_solve_inequality(Relational(expr, 0, rel), gen))
  737. continue
  738. else:
  739. raise NotImplementedError(filldedent('''
  740. inequality has more than one symbol of interest.
  741. '''))
  742. if expr.is_polynomial(gen):
  743. poly_part.setdefault(gen, []).append((expr, rel))
  744. else:
  745. components = expr.find(lambda u:
  746. u.has(gen) and (
  747. u.is_Function or u.is_Pow and not u.exp.is_Integer))
  748. if components and all(isinstance(i, Abs) for i in components):
  749. abs_part.setdefault(gen, []).append((expr, rel))
  750. else:
  751. other.append(_solve_inequality(Relational(expr, 0, rel), gen))
  752. poly_reduced = [reduce_rational_inequalities([exprs], gen) for gen, exprs in poly_part.items()]
  753. abs_reduced = [reduce_abs_inequalities(exprs, gen) for gen, exprs in abs_part.items()]
  754. return And(*(poly_reduced + abs_reduced + other))
  755. def reduce_inequalities(inequalities, symbols=[]):
  756. """Reduce a system of inequalities with rational coefficients.
  757. Examples
  758. ========
  759. >>> from sympy.abc import x, y
  760. >>> from sympy import reduce_inequalities
  761. >>> reduce_inequalities(0 <= x + 3, [])
  762. (-3 <= x) & (x < oo)
  763. >>> reduce_inequalities(0 <= x + y*2 - 1, [x])
  764. (x < oo) & (x >= 1 - 2*y)
  765. """
  766. if not iterable(inequalities):
  767. inequalities = [inequalities]
  768. inequalities = [sympify(i) for i in inequalities]
  769. gens = set().union(*[i.free_symbols for i in inequalities])
  770. if not iterable(symbols):
  771. symbols = [symbols]
  772. symbols = (set(symbols) or gens) & gens
  773. if any(i.is_extended_real is False for i in symbols):
  774. raise TypeError(filldedent('''
  775. inequalities cannot contain symbols that are not real.
  776. '''))
  777. # make vanilla symbol real
  778. recast = {i: Dummy(i.name, extended_real=True)
  779. for i in gens if i.is_extended_real is None}
  780. inequalities = [i.xreplace(recast) for i in inequalities]
  781. symbols = {i.xreplace(recast) for i in symbols}
  782. # prefilter
  783. keep = []
  784. for i in inequalities:
  785. if isinstance(i, Relational):
  786. i = i.func(i.lhs.as_expr() - i.rhs.as_expr(), 0)
  787. elif i not in (True, False):
  788. i = Eq(i, 0)
  789. if i == True:
  790. continue
  791. elif i == False:
  792. return S.false
  793. if i.lhs.is_number:
  794. raise NotImplementedError(
  795. "could not determine truth value of %s" % i)
  796. keep.append(i)
  797. inequalities = keep
  798. del keep
  799. # solve system
  800. rv = _reduce_inequalities(inequalities, symbols)
  801. # restore original symbols and return
  802. return rv.xreplace({v: k for k, v in recast.items()})