inequalities.py 32 KB

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