K idZddlmZddlmZmZmZmZmZm Z ddl m Z ddl m Z ddlmZmZmZmZmZmZmZmZmZmZmZddlmZmZddlmZmZm Z dd l!m"Z"m#Z#dd l$m%Z%dd l&m'Z'm(Z(dd l)m*Z*m+Z+dd l,m-Z-m.Z.ddl/m0Z0ddl1m2Z2m3Z3ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBmCZCddlDmEZEddlFmGZGddlHmIZImJZJddlKmLZLddlMmNZNddlOmPZPddlQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\ddl]m^Z^ddl_m`Z`maZambZbmcZcddldmeZeddlfmgZgddlhmiZimjZjddlkmlZlmmZmmnZnmoZoddlpmqZqmrZrddlsmtZtmuZudd lvmwZwdd!lxmyZydd"lzm{Z{m|Z|dd#l}m~Z~mZmZmZmZmZmZmZdd$lmZdd%lmZdd&lmZdd'lmZdd(lmZdd)lmZmZdd*lZd+Zd,Zd-Zd.ZdHd/Zd0Zd1Zd2Z dId3Zd4Zdggfd5Zd6Zd7Zd8Zd9Zd:Zd;ZdHd<Zd=Ze9d>e8d?iZd@ZdAZedBdCdDZdEZdFZddGlmZmZmZy*)Ja This module contain solvers for all kinds of equations: - algebraic or transcendental, use solve() - recurrence, use rsolve() - differential, use dsolve() - nonlinear (numerically), use nsolve() (you will need a good starting point) ) annotations)SAddSymbolDummyExprMul)check_assumptions) factor_terms) expand_mul expand_log Derivative AppliedUndefUndefinedFunctionnfloatFunctionexpand_power_exp_mexpandexpand expand_func) fuzzy_not fuzzy_and)FloatRational_illegal) integer_logilcm)Pow)EqNe)ordereddefault_sort_key)sympify_sympify)preorder_traversal)And BooleanAtom)logexpLambertWcossintanacosasinatanAbsreimargsqrtatan2)binomial)HyperbolicFunction)piecewise_fold Piecewise)TrigonometricFunction)Integral)divisors) simplifycollectpowsimpposify powdenest nsimplifydenom logcombine sqrtdenestfraction separatevars) sqrt_depth)TR1TR2iTR10TR11)rebuild)NonInvertibleMatrixError)Matrixzeros)rootscancelfactorPoly)sympy_eqs_to_ring solve_lin_sys)GeneratorsNeededPolynomialError)gcd)lambdify) filldedentdebugf)connected_components generate_belluniqiterable is_sequencesubsetsflattensift)conserve_mpmath_dps)findroot)solve_poly_system) GeneratorType) defaultdict) combinationsproductNct|st|r tdt|}tt|}i}d}|D].}t |t r||vst d|z||<|dz }0g}|D]:}t|dd}||j||*|j|<|jD cic]\}} | | } }} ||Dcgc]}|j||c}| fScc} }wcc}w)a Return (e, s, d) where e and s are versions of *eqs* and *symbols* in which any non-Symbol objects in *symbols* have been replaced with generic Dummy symbols and d is a dictionary that can be used to restore the original expressions. Examples ======== >>> from sympy.solvers.solvers import recast_to_symbols >>> from sympy import symbols, Function >>> x, y = symbols('x y') >>> fx = Function('f')(x) >>> eqs, syms = [fx + 1, x, y], [fx, y] >>> e, s, d = recast_to_symbols(eqs, syms); (e, s, d) ([_X0 + 1, x, y], [_X0, y], {_X0: f(x)}) The original equations and symbols can be restored using d: >>> assert [i.xreplace(d) for i in eqs] == eqs >>> assert [d.get(i, i) for i in s] == syms z%Both eqs and symbols must be iterablerzX%dsubsN) ra ValueErrorlistr! isinstancerrgetattrappenditemsget) eqssymbolsorigswap_symisnew_fisubskvrestores [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/solvers/solvers.pyrecast_to_symbolsrFs0 C=Xg.@AA =D77#$GH A !V$(): *HQK FA E 64(   LLx ) LLO  !) 011q!t1G1 t4!8<<1%4g ==24s C?!Dcbt|txr|jxst|tS)z$Return True if e is a Pow or is exp.)rrris_Powr)es r_ispowrss$ a  CAHH$B 1c0BCct}t||D]X}|jr9|jjr#|jj r<|j }|j|Z|SN)setdenomsrr) is_Numberis_zerobaseadd)frxdensds r _simple_densrxs[ 5D Aw  88uu}}A   Krct|}t}|D]U}t|tst |}|t j ur2|jtj|W|s|St|dk(rt|dr|d}|Dchc]tfd|Dsc}Scc}w)aV Return (recursively) set of all denominators that appear in *eq* that contain any symbol in *symbols*; if *symbols* are not provided then all denominators will be returned. Examples ======== >>> from sympy.solvers.solvers import denoms >>> from sympy.abc import x, y, z >>> denoms(x/y) {y} >>> denoms(x/(y*z)) {y, z} >>> denoms(3/x + y/z) {x, z} >>> denoms(x/2 + y/z) {2, z} If *symbols* are provided then only denominators containing those symbols will be returned: >>> denoms(1/x + 1/y + 1/z, y, z) {y, z} rnrc3:K|]}|jvywr free_symbols).0r|rs r zdenoms..s"H11#6"H) r%rrrrrDrOneupdater make_argslenraany)eqrxpotrpdenrs `rrrs@ R C 5D (!T" Ah !%%<  CMM#&'(  W  GAJ ajG I!s"H"HHA II Is B<5B<c X ddlm}jdd}|in%t|tr|nd}t ||fzt |r"|s t dtfd|DSt|}|jr |jSt|tr|j}nt|ttfr|jt j"t j$fvr |j&}|j(\}}t|t*r|j-}|j.s4yt|tr#t1|j2|j d }t|t*r t5|S|j6s|sy t9t:t=fd j?Dryd } jd d } | dz } | dk(rJ|j-} t| t@r| jC|d} | jEzry| dk(rk js| jFtIjKd| isy| jM\} } tO| jQdd } nu| dk(r|ryjdd rD]} tS| | <tS|j-} jdd rtU| \} }tO| d }|jr|} ntWtY }t9}d}|D]b}||vr|j[||j\r|j^j`sd }n!|jbrd }nt|tdrd }|sbn|duryjdd r| j-} tg| j}|%| jr| jitjry| Sn_| jlr| dk(S| rJ| jr>to| jqdjqdd dkt j"uSjddrtsjtdzyy)a Checks whether sol is a solution of equation f == 0. Explanation =========== Input can be either a single symbol and corresponding value or a dictionary of symbols and values. When given as a dictionary and flag ``simplify=True``, the values in the dictionary will be simplified. *f* can be a single equation or an iterable of equations. A solution must satisfy all equations in *f* to be considered valid; if a solution does not satisfy any equation, False is returned; if one or more checks are inconclusive (and none are False) then None is returned. Examples ======== >>> from sympy import checksol, symbols >>> x, y = symbols('x,y') >>> checksol(x**4 - 1, x, 1) True >>> checksol(x**4 - 1, x, 0) False >>> checksol(x**2 + y**2 - 5**2, {x: 3, y: 4}) True To check if an expression is zero using ``checksol()``, pass it as *f* and send an empty dictionary for *symbol*: >>> checksol(x**2 + x - x*(x + 1), {}) True None is returned if ``checksol()`` could not conclude. flags: 'numerical=True (default)' do a fast numerical check if ``f`` has only one symbol. 'minimal=True (default is False)' a very fast, minimal testing. 'warn=True (default is False)' show a warning if checksol() could not conclude. 'simplify=True (default)' simplify solution before substituting into function and simplify the function before trying specific simplifications 'force=True (default is False)' make positive all symbols without assumptions regarding sign. r)UnitminimalFNz;Expecting (sym, val) or ({sym: val}, None) but got (%s, %s)zno functions to checkc38K|]}t|fiywrchecksol)rfiflagssols rrzchecksol..s@"c3U3@evaluateTc3\K|]#\}}t|jz%ywr)r#atoms)rrrillegals rrzchecksol..s' @DAq71:    ' @s), numericalrnr> recursiveforce )chopg& .>warnz( Warning: could not verify solution %s.);sympy.physics.unitsrrvrrdictrprarr$ is_numberrrUas_exprrr rhsrtruefalsereversedargsr'ro is_Booleanrlhsbool is_Relationalrrrrur as_independentr is_constantrqkeysas_content_primitiveras_numer_denomr>rAr%r rrr) is_Integer is_Functionrrhasr* is_Rationalabsnwarningsr)rsymbolrrrrmsgBEattemptrval_rrepsexvalrseen saw_pow_funcrnzrs `` @rrrsb)ii 5)G sm FD !K},--{45 5@a@@@ A{{yy!T IIK ABx 55QVVQWW% % Avv1 a %s A<< 2 AEEAEE6E2A![!Aw __Q(mG @CIIK @@G +t,I 1  a<&&+C#s#((.q1yy{W$ \==&sSXXZ(8Ow;O 1133s113A6$G \yyT*.A%c!f-CF.166#;'Cyy$'"3K T 5??C%Z_5C5D L 9 88AEE$4$4#'L]]#'L#45#'L u$yy$'hhtn3;;'B~ ==SWWX%6 v  ??!8O b BT 23d:qvvE ES V yy BSHI rc:;<ddlm}d}d}|D]-}|j|t|j ||}/|j dd}|j dd}|j dd} t | } |j d d |j d d s t d |j d dr| rt td d;;fd|fD\}d } stj|D cgc]} | jc} tt|krR|D]M} t| } | D];}t|ts| sd|d<j|| j!=Od} t#t%nztdk(rt drdxrt't(} t#t+}t|tk7rd} t#t%n|tttk7r t d|j-dt}|r`t|t.r|g}tjt1|Dcgc]}|jc}}Dcgc] }||vs| c}t|t"r"|Dcgc]}|t2j4us|}}t7|D]\}} t| t8t:fr-d| j<Dcgc]}t?|j@c}vr| jB| jDz } n| j<\}}t|tFr||}}t|tFryt| t:r|}|jHr|t2jJur|n|} nu|jLr|cS|jNr|jLr|cStQtdt| t8r#tS| jB| jD d} | ||<| jHrZtdk7r t d|r3djTr$tWjXtddz||cSt| tZr| j]||<||j_fdd||<||j`rI ||jc||<d} |jet#||t2jf||<||j}|s[tid|Dso||jk\}} ||jmtntptrtt<|s| s|| k7stw| jr | jr| jr>> from sympy import solve, Poly, Eq, Matrix, Symbol >>> from sympy.abc import x, y, z, a, b The expressions that are passed can be Expr, Equality, or Poly classes (or lists of the same); a Matrix is considered to be a list of all the elements of the matrix: >>> solve(x - 3, x) [3] >>> solve(Eq(x, 3), x) [3] >>> solve(Poly(x - 3), x) [3] >>> solve(Matrix([[x, x + y]]), x, y) == solve([x, x + y], x, y) True If no symbols are indicated to be of interest and the equation is univariate, a list of values is returned; otherwise, the keys in a dictionary will indicate which (of all the variables used in the expression(s)) variables and solutions were found: >>> solve(x**2 - 4) [-2, 2] >>> solve((x - a)*(y - b)) [{a: x}, {b: y}] >>> solve([x - 3, y - 1]) {x: 3, y: 1} >>> solve([x - 3, y**2 - 1]) [{x: 3, y: -1}, {x: 3, y: 1}] If you pass symbols for which solutions are sought, the output will vary depending on the number of symbols you passed, whether you are passing a list of expressions or not, and whether a linear system was solved. Uniform output is attained by using ``dict=True`` or ``set=True``. >>> #### *** feel free to skip to the stars below *** #### >>> from sympy import TableForm >>> h = [None, ';|;'.join(['e', 's', 'solve(e, s)', 'solve(e, s, dict=True)', ... 'solve(e, s, set=True)']).split(';')] >>> t = [] >>> for e, s in [ ... (x - y, y), ... (x - y, [x, y]), ... (x**2 - y, [x, y]), ... ([x - 3, y -1], [x, y]), ... ]: ... how = [{}, dict(dict=True), dict(set=True)] ... res = [solve(e, s, **f) for f in how] ... t.append([e, '|', s, '|'] + [res[0], '|', res[1], '|', res[2]]) ... >>> # ******************************************************* # >>> TableForm(t, headings=h, alignments="<") e | s | solve(e, s) | solve(e, s, dict=True) | solve(e, s, set=True) --------------------------------------------------------------------------------------- x - y | y | [x] | [{y: x}] | ([y], {(x,)}) x - y | [x, y] | [(y, y)] | [{x: y}] | ([x, y], {(y, y)}) x**2 - y | [x, y] | [(x, x**2)] | [{y: x**2}] | ([x, y], {(x, x**2)}) [x - 3, y - 1] | [x, y] | {x: 3, y: 1} | [{x: 3, y: 1}] | ([x, y], {(3, 1)}) * If any equation does not depend on the symbol(s) given, it will be eliminated from the equation set and an answer may be given implicitly in terms of variables that were not of interest: >>> solve([x - y, y - 3], x) {x: y} When you pass all but one of the free symbols, an attempt is made to find a single solution based on the method of undetermined coefficients. If it succeeds, a dictionary of values is returned. If you want an algebraic solutions for one or more of the symbols, pass the expression to be solved in a list: >>> e = a*x + b - 2*x - 3 >>> solve(e, [a, b]) {a: 2, b: 3} >>> solve([e], [a, b]) {a: -b/x + (2*x + 3)/x} When there is no solution for any given symbol which will make all expressions zero, the empty list is returned (or an empty set in the tuple when ``set=True``): >>> from sympy import sqrt >>> solve(3, x) [] >>> solve(x - 3, y) [] >>> solve(sqrt(x) + 1, x, set=True) ([x], set()) When an object other than a Symbol is given as a symbol, it is isolated algebraically and an implicit solution may be obtained. This is mostly provided as a convenience to save you from replacing the object with a Symbol and solving for that Symbol. It will only work if the specified object can be replaced with a Symbol using the subs method: >>> from sympy import exp, Function >>> f = Function('f') >>> solve(f(x) - x, f(x)) [x] >>> solve(f(x).diff(x) - f(x) - x, f(x).diff(x)) [x + f(x)] >>> solve(f(x).diff(x) - f(x) - x, f(x)) [-x + Derivative(f(x), x)] >>> solve(x + exp(x)**2, exp(x), set=True) ([exp(x)], {(-sqrt(-x),), (sqrt(-x),)}) >>> from sympy import Indexed, IndexedBase, Tuple >>> A = IndexedBase('A') >>> eqs = Tuple(A[1] + A[2] - 3, A[1] - A[2] + 1) >>> solve(eqs, eqs.atoms(Indexed)) {A[1]: 1, A[2]: 2} * To solve for a function within a derivative, use :func:`~.dsolve`. To solve for a symbol implicitly, use implicit=True: >>> solve(x + exp(x), x) [-LambertW(1)] >>> solve(x + exp(x), x, implicit=True) [-exp(x)] It is possible to solve for anything in an expression that can be replaced with a symbol using :obj:`~sympy.core.basic.Basic.subs`: >>> solve(x + 2 + sqrt(3), x + 2) [-sqrt(3)] >>> solve((x + 2 + sqrt(3), x + 4 + y), y, x + 2) {y: -2 + sqrt(3), x + 2: -sqrt(3)} * Nothing heroic is done in this implicit solving so you may end up with a symbol still in the solution: >>> eqs = (x*y + 3*y + sqrt(3), x + 4 + y) >>> solve(eqs, y, x + 2) {y: -sqrt(3)/(x + 3), x + 2: -2*x/(x + 3) - 6/(x + 3) + sqrt(3)/(x + 3)} >>> solve(eqs, y*x, x) {x: -y - 4, x*y: -3*y - sqrt(3)} * If you attempt to solve for a number, remember that the number you have obtained does not necessarily mean that the value is equivalent to the expression obtained: >>> solve(sqrt(2) - 1, 1) [sqrt(2)] >>> solve(x - y + 1, 1) # /!\ -1 is targeted, too [x/(y - 1)] >>> [_.subs(z, -1) for _ in solve((x - y + 1).subs(-1, z), 1)] [-x + y] **Additional Examples** ``solve()`` with check=True (default) will run through the symbol tags to eliminate unwanted solutions. If no assumptions are included, all possible solutions will be returned: >>> x = Symbol("x") >>> solve(x**2 - 1) [-1, 1] By setting the ``positive`` flag, only one solution will be returned: >>> pos = Symbol("pos", positive=True) >>> solve(pos**2 - 1) [1] When the solutions are checked, those that make any denominator zero are automatically excluded. If you do not want to exclude such solutions, then use the check=False option: >>> from sympy import sin, limit >>> solve(sin(x)/x) # 0 is excluded [pi] If ``check=False``, then a solution to the numerator being zero is found but the value of $x = 0$ is a spurious solution since $\sin(x)/x$ has the well known limit (without discontinuity) of 1 at $x = 0$: >>> solve(sin(x)/x, check=False) [0, pi] In the following case, however, the limit exists and is equal to the value of $x = 0$ that is excluded when check=True: >>> eq = x**2*(1/x - z**2/x) >>> solve(eq, x) [] >>> solve(eq, x, check=False) [0] >>> limit(eq, x, 0, '-') 0 >>> limit(eq, x, 0, '+') 0 **Solving Relationships** When one or more expressions passed to ``solve`` is a relational, a relational result is returned (and the ``dict`` and ``set`` flags are ignored): >>> solve(x < 3) (-oo < x) & (x < 3) >>> solve([x < 3, x**2 > 4], x) ((-oo < x) & (x < -2)) | ((2 < x) & (x < 3)) >>> solve([x + y - 3, x > 3], x) (3 < x) & (x < oo) & Eq(x, 3 - y) Although checking of assumptions on symbols in relationals is not done, setting assumptions will affect how certain relationals might automatically simplify: >>> solve(x**2 > 4) ((-oo < x) & (x < -2)) | ((2 < x) & (x < oo)) >>> r = Symbol('r', real=True) >>> solve(r**2 > 4) (2 < r) | (r < -2) There is currently no algorithm in SymPy that allows you to use relationships to resolve more than one variable. So the following does not determine that ``q < 0`` (and trying to solve for ``r`` and ``q`` will raise an error): >>> from sympy import symbols >>> r, q = symbols('r, q', real=True) >>> solve([r + q - 3, r > 3], r) (3 < r) & Eq(r, 3 - q) You can directly call the routine that ``solve`` calls when it encounters a relational: :func:`~.reduce_inequalities`. It treats Expr like Equality. >>> from sympy import reduce_inequalities >>> reduce_inequalities([x**2 - 4]) Eq(x, -2) | Eq(x, 2) If each relationship contains only one symbol of interest, the expressions can be processed for multiple symbols: >>> reduce_inequalities([0 <= x - 1, y < 3], [x, y]) (-oo < y) & (1 <= x) & (x < oo) & (y < 3) But an error is raised if any relationship has more than one symbol of interest: >>> reduce_inequalities([0 <= x*y - 1, y < 3], [x, y]) Traceback (most recent call last): ... NotImplementedError: inequality has more than one symbol of interest. **Disabling High-Order Explicit Solutions** When solving polynomial expressions, you might not want explicit solutions (which can be quite long). If the expression is univariate, ``CRootOf`` instances will be returned instead: >>> solve(x**3 - x + 1) [-1/((-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)) - (-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3, -(-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/((-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)), -(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/(3*sqrt(69)/2 + 27/2)**(1/3)] >>> solve(x**3 - x + 1, cubics=False) [CRootOf(x**3 - x + 1, 0), CRootOf(x**3 - x + 1, 1), CRootOf(x**3 - x + 1, 2)] If the expression is multivariate, no solution might be returned: >>> solve(x**3 - x + a, x, cubics=False) [] Sometimes solutions will be obtained even when a flag is False because the expression could be factored. In the following example, the equation can be factored as the product of a linear and a quadratic factor so explicit solutions (which did not require solving a cubic expression) are obtained: >>> eq = x**3 + 3*x**2 + x - 1 >>> solve(eq, cubics=False) [-1, -1 + sqrt(2), -sqrt(2) - 1] **Solving Equations Involving Radicals** Because of SymPy's use of the principle root, some solutions to radical equations will be missed unless check=False: >>> from sympy import root >>> eq = root(x**3 - 3*x**2, 3) + 1 - x >>> solve(eq) [] >>> solve(eq, check=False) [1/3] In the above example, there is only a single solution to the equation. Other expressions will yield spurious roots which must be checked manually; roots which give a negative argument to odd-powered radicals will also need special checking: >>> from sympy import real_root, S >>> eq = root(x, 3) - root(x, 5) + S(1)/7 >>> solve(eq) # this gives 2 solutions but misses a 3rd [CRootOf(7*x**5 - 7*x**3 + 1, 1)**15, CRootOf(7*x**5 - 7*x**3 + 1, 2)**15] >>> sol = solve(eq, check=False) >>> [abs(eq.subs(x,i).n(2)) for i in sol] [0.48, 0.e-110, 0.e-110, 0.052, 0.052] The first solution is negative so ``real_root`` must be used to see that it satisfies the expression: >>> abs(real_root(eq.subs(x, sol[0])).n(2)) 0.e-110 If the roots of the equation are not real then more care will be necessary to find the roots, especially for higher order equations. Consider the following expression: >>> expr = root(x, 3) - root(x, 5) We will construct a known value for this expression at x = 3 by selecting the 1-th root for each radical: >>> expr1 = root(x, 3, 1) - root(x, 5, 1) >>> v = expr1.subs(x, -3) The ``solve`` function is unable to find any exact roots to this equation: >>> eq = Eq(expr, v); eq1 = Eq(expr1, v) >>> solve(eq, check=False), solve(eq1, check=False) ([], []) The function ``unrad``, however, can be used to get a form of the equation for which numerical roots can be found: >>> from sympy.solvers.solvers import unrad >>> from sympy import nroots >>> e, (p, cov) = unrad(eq) >>> pvals = nroots(e) >>> inversion = solve(cov, x)[0] >>> xvals = [inversion.subs(p, i) for i in pvals] Although ``eq`` or ``eq1`` could have been used to find ``xvals``, the solution can only be verified with ``expr1``: >>> z = expr - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z.subs(x, xi).n()) < 1e-9] [] >>> z1 = expr1 - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z1.subs(x, xi).n()) < 1e-9] [-3.0] Parameters ========== f : - a single Expr or Poly that must be zero - an Equality - a Relational expression - a Boolean - iterable of one or more of the above symbols : (object(s) to solve for) specified as - none given (other non-numeric objects will be used) - single symbol - denested list of symbols (e.g., ``solve(f, x, y)``) - ordered iterable of symbols (e.g., ``solve(f, [x, y])``) flags : dict=True (default is False) Return list (perhaps empty) of solution mappings. set=True (default is False) Return list of symbols and set of tuple(s) of solution(s). exclude=[] (default) Do not try to solve for any of the free symbols in exclude; if expressions are given, the free symbols in them will be extracted automatically. check=True (default) If False, do not do any testing of solutions. This can be useful if you want to include solutions that make any denominator zero. numerical=True (default) Do a fast numerical check if *f* has only one symbol. minimal=True (default is False) A very fast, minimal testing. warn=True (default is False) Show a warning if ``checksol()`` could not conclude. simplify=True (default) Simplify all but polynomials of order 3 or greater before returning them and (if check is not False) use the general simplify function on the solutions and the expression obtained when they are substituted into the function which should be zero. force=True (default is False) Make positive all symbols without assumptions regarding sign. rational=True (default) Recast Floats as Rational; if this option is not used, the system containing Floats may fail to solve because of issues with polys. If rational=None, Floats will be recast as rationals but the answer will be recast as Floats. If the flag is False then nothing will be done to the Floats. manual=True (default is False) Do not use the polys/matrix method to solve a system of equations, solve them one at a time as you might "manually." implicit=True (default is False) Allows ``solve`` to return a solution for a pattern in terms of other functions that contain that pattern; this is only needed if the pattern is inside of some invertible function like cos, exp, etc. particular=True (default is False) Instructs ``solve`` to try to find a particular solution to a linear system with as many zeros as possible; this is very expensive. quick=True (default is False; ``particular`` must be True) Selects a fast heuristic to find a solution with many zeros whereas a value of False uses the very slow method guaranteed to find the largest number of zeros possible. cubics=True (default) Return explicit solutions when cubic expressions are encountered. When False, quartics and quintics are disabled, too. quartics=True (default) Return explicit solutions when quartic expressions are encountered. When False, quintics are disabled, too. quintics=True (default) Return explicit solutions (if possible) when quintic expressions are encountered. See Also ======== rsolve: For solving recurrence relationships sympy.solvers.ode.dsolve: For solving differential equations rn)reduce_inequalitiescubicsquarticsquinticsTimplicitFrrquickN particularz/when using `quick`, `particular` should be Truez The 'particular/quick' flag is usually used with systems of equations. Either pass your equation in a list or consider using a solver like `diophantine` if you are looking for a solution in integers.c`tttt|r |S|gSr)rqmapr#raws r_sympified_listzsolve.._sympified_listbs'Chqk;<<s;<.ds;/!$;rr)includezduplicate symbols givenexcludeImmutableDenseMatrixz Unanticipated argument of Eq when other arg is True or False. rz'can only solve for one symbol at a timezm Warning: assumptions about variable '%s' are not handled currently.rxcFt|txr|jSr)rrr8has_free)rrxs rzsolve..s%j4F&G'! AJJ rc,|jtSr)rewriter)rs rrzsolve..sAIIcNrz1solve cannot handle matrices with symbolic shape.c3PK|]}|jxs |j ywr)is_extended_real is_imaginaryrr|s rrzsolve..s"M!++=q~~=Ms$&c3lK|]+}|jttttz -ywr)rr2r3r4r6)rr{hads rrzsolve..s,2I:;AGGBC/#52Is14c3HK|]}t|ttfywr)rrrr')rrs rrzsolve..s ;2:b4- . ;s "c|jr'tt|jtSt|Sr)rrHr1rr:)r4rxs rrzsolve..s8=DSWWg=N SX&..y9Xrz6solving %s when the argument is not real or imaginary.cdt|jtjtSr)r4rr6r0)as rrzsolve..ss1v~~e'<'D'DT'Jrc3fK|](}|jtt*ywr)rr2r3)rrr|s rrzsolve..s$8B266"Q%A'8s.1rational)r  _denominatorscv|jr|jStfd|jDS)Nc3.K|] }|ywrr)rr_has_piecewises rrz0solve.._has_piecewise..ls5>!$5r) is_Piecewiserrr)rr rxs rr zsolve.._has_piecewiseis/ >>155'? "5aff555rc4|jdjSNr)ris_Addxs rrzsolve..xs166!9+;+;r)binaryrc |Dcgc]+}tDcgc]}|j||c}-c}}Scc}wcc}}wr)tuplerv)r|r{rrxs rrzsolve..s2QOe'$BQQUU1a[$BCO$BOsA; AAc:|Dcgc] }|d c}Scc}wrr)r|r{rxs rrzsolve..sq9!'!* 99sc |dSrrr|s rrzsolve..s qtrc|Srrrs rrzsolve..sqrc |dSrrrs rrzsolve..s 1Q4rc|Srrrs rrzsolve..s1rcheck)exponentc3NK|]\}}t|fi|jywr)r assumptions0)rsymbrs rrzsolve..s,8'dC,CE43D3DE8#%zl Warning: assumptions concerning following solution(s) cannot be checked: , c32K|]}t|ywr)strrs rrzsolve..s3Q#a&3keyc3NK|]}t|jywr)rrrr{s rrzsolve.. s$GU1668_$Gr")j inequalitiesr setdefaultrrvrarpr\runionrrr%rrrrskiprqr!rbrir`poprr#rr enumeraterr rtype__name__rrr'rr is_SymbolrNotImplementedErrorrr rrrUrreplace is_Matrix as_explicitextendZeroall as_real_imagrr2r3r4r6rr1findris_realrrt ImaginaryUnitxreplacerrrrrr:ris_MulrrfuncrziprrorurrCrr9r;rerrrLrZrM_solve_undetermined_solve _solve_systemr_remove_duplicate_solutionsrjoinsortr"rdr)=rrxrrhintsdefaultrrras_setbare_fordered_symbolsrrr_symbolsrrr|r{rLRfreeifrwasfreimirfrrzsymsetnewfokr non_invertsrrfloatsttargsrotherltrepinddeprrsolutionlinearas_dict tuple_formatunpackrrgot_Noneno_Falsekir rrs= ` ` @@@rsolverjjsG`2 /EG C""1d599Q+@&ABCyyU+H 99VU #DYYue $F!_F yy$+yyt,NO O yyu%&%345 5=;q'l;JAw O #%++!3 B'RVVbffWu=BAaD   7|q  !JKK // j*.07 *;<='q': : b$ ::> t'')! F HHT!A$Z 66AaD!!! SMuMMqT&&(FBA$**RS%0CbR2Xc2I@BBx2I/I"F!2h!QU ID'N ; ;; su9  12CC"Bby  5Aquug)+023+455 5 ZZJ K!', .Brvvb"~R .E .  ?AyyANN8%88 Ar!uqr!u'<<=>  ?  /3567rR[[!S*71s7)C1r!u~. / E&M-Q8Aw \F D ??V #B||<<zz I>>#B KKO9:  CE> !  A 5D%K $ Aa&*Q *BQ%KHHHHXMM(r2h8N$ >>F*OOA& HHJ! & tC {-K!eg-KLMNK()*" *A*ITHYHYH[\1Aqzz(+00:;\K\F yyT"%/q\ 4EArvve} d3! 4*!A$8E/ 61&2 " !"%AaD& D2BHH-B$C DqQ DQ DE D 5zA~%!;DI UGJElS!T !! !4 ,4>h> 4 ii&GPL&  w<1 9F ]a C $4G $D#F !F F #h-1,( %$FtH~-9: B1Q{++B/67!8<<1%7) /FAs"%))+/!Q$<<1-qvvh/??/HQK / IIgt $E(uyyT:B(U3.x8 yy' %C8+.99;88AEz OOC y$ % H MM*&/ 3(33&45 6  CE> !  ;CDagaj1Q!W1DD * + gh  W$Gh$GGHI J 8Daua0aeeBm01D DD} =@ J: . *M`  G ` /8\.L*]> E=S3 ,dC8/Z2D,1Ds }(}-1 }2;}2}7.}7,}<?~~2~8~~#&~(,~-#~3( ~>1~9 ~9 ~>: 4 (88, .+ & +361 6~9~>&+16c |jt|z r*t||fit|dd}t |dk(r|Syy)asolve helper to return a list with one dict (solution) else None A direct call to solve_undetermined_coeffs is more flexible and can return both multiple solutions and handle more than one independent variable. Here, we have to be more cautious to keep from solving something that does not look like an undetermined coeffs system -- to minimize the surprise factor since singularities that cancel are not prohibited in solve_undetermined_coeffs. TN)rrrn)rrsolve_undetermined_coeffsrr)grxrrs rrCrC sI ~~G $'7Wd5tQU6VW s8q=J %rc ZCd}t|dk7r g}t}t}g}|D]t|g\}} |k(rYjddr t | } | j } | |zrH|| z}|j ||j|| ir|su|j|s|S|D]L t|fi} | D]7} | j |zr|j |j| 9N|r|St||z|dC|jCfdd}jd dxd <x} }|jrt}|jD]f}|tjtj tj"hvr t}n)t%|Cfi} |j't| h|D cgc]} C| i}} |rAjd t)||}|Dcgc]t+fd |Ds}}d }d d<n_|j,r?t}t+d |jDr|j }dx}}|jD]\}}t/||}t/||}|j0r*|j d k7rtt3d|zt%|Cfi}|D]~}||vr |j5C|} t7| dd}| |dd} | d k(r;| dk(r|j |R|j t;|| ftj<df|Dcgc]}C|ic}St||\}} |j0s| tj<urgS|j>r"jddr t | } || igSd}|j@sz|jCtDDcgc]}C|j vr|}}t|dk(r<|d}|jGCdjId}|Ck(r tK||}d }d} | tK|}|tOd|z |jRD"cgc]}"|"jUCs|"}#}"d}$t|#dkDr}tWtY|#D"cgc] }"|$|" c}"\}%}&t|%}%t|%dkDst[d|&Dsw|%D'chc]}'|'j\s|'}(}'|(D)chc]})t_|)t`r|)}*})|(|*z }+|+st|(jc|*dkDrkd},|j@r t|jdk(r|j}-|-Dcgc]&}|jCtdjc|*(c}x}.\}/}'t[d|.Dr|.Dcgc]}|jc}\}/}'t_|/tfr |'|/}'}/|-ddd}-t_|/thret_|'tfrU|/jd|'jdk(r6tk|-d|-dz dzjm\},}0|0jnsd},|,tq|jstt},|,|k7rd d <t|,Cfi}|d <|d ur|(rtWtw|(}(|(d}1tyd}.|j5|1|.}2|2jUCsRt|2|.fi}3tWtwt%|.|1z Cfid}4|3D cgc]} C|4j5| i}} |d ur d|#z} n|%j}5tyd}.t%|5|.z Cfi}6t_|5tzt|frd}7|jd|7j5|5|.}2|2jUCst|2|.fi} |6Dcgc]}| D]}C|j5|i}}}nPt|#dk(rAtK||#dd}jd d sd} |j}8dd <d!}9|9D:cic]}:|:j|:};}:t|fi|;} t| j|8kr |j} ntW| j} | }|j}5|5Ck7rE tyd}.t%|5|.z Cfi}6|6Dchc]}| D]}|j5|.|} }}nd }| #t| dkDrjdd d<| | D cgc]} C| i}} |d urjd$dr tC}5|5r|5\}<}=|=r?|=\}>}?t%|?Cfid}6t|<|>fiDchc]}|6j5|}@}n tt%|TrcJt|txr|jSr)rrr7r)rrs rrz_solve..asJq(3Ef rct|Sr)rrs rrz_solve..bs +a.rrr c38K|]}t|fiywrr)rrrr|s rrz_solve..ys!ca151rFc3:K|]\}}|jywr)r)rrcs rrz_solve..s,TQqyy,saz An expression is already zero when %s. This means that in this *region* the solution is zero but solve can only represent discrete, not interval, solutions. If this is a spurious interval it might be resolved with simplification of the Piecewise conditions._eval_simplifyNrcyNrnrrs rrz_solve..sr)ratiomeasurezcould not convert %s to Polyz#expression appears to be a constantc|j\}}|jr||jfS|js|dfS|j \}}|jr#|t j ur||z|jfS|dfS)zReturn (b**e, q) for x = b**(p*e/q) where p/q is the leading Rational of the exponent of x, e.g. exp(-2*x/3) -> (exp(x), 3) rn) as_base_exprqr@ as_coeff_Mulrr)rbrrsees r _as_base_qz_solve.._as_base_qss==?DAq}}!##v 88!t NN$EAr}}!%%"uaccz!a4Krc3&K|] }|dk( ywrnNr)rr|s rrz_solve..s(. s6qs1v{6rr[zmultiple generators %scZ|j\}}t|}t||zSr)r{r r)rr~rs r_expandz_solve.._expandDs) }}1&qM/155rc>|jxst|tSr)rrrr)rs rrz_solve..Is!(("@jC.@r) compositetsolver incompletea Neither high-order multivariate polynomials nor sorting of EX-domain polynomials is supported. If you want to see any results, pass keyword incomplete=True to solve; to see numerical values of roots for univariate expressions, use nroots. _unrad c38K|]}t|fiywrrrrrrs rrz_solve..s%)#1a151)r)Krr solve_linearrvr>rrrtrDr4r5r/r@rrNegativeInfinityComplexInfinityInfinity_vsolverrrrr&rr\rors TypeErrorr:NaNr3rrrrr{rUrYrprXgensrrqrBr:rrrr; intersectionrr+r,rKrrrJrr-r!rrr)degreerRsumvalues all_rootsrgenunrad_tsolverGrFr)Drrxr not_impl_msgnonlin_sgot_srhs_sresultxirvfreesolnr checkdensrmrr|condnegexprcnd candidates candidatertrf_numpolyr{add_argsrspartr simplified_frmrrbasesqsr~funcsrtrigr]rW_argsr[r_df1ftrycv_solscv_invuinvrdegrIhsolversrcovisymieqrvrrrsD ` ` ` @rrDrDsZ HL 7|q #A QC0EBQw99Z.  A5= "  r1g&"! #"M A a,e,'C1v**U2 IIaLMM#& '  M%lQ&67 7QZF E  "A */7D)AAE'NAY xx %AQ''):):AJJGG1f..D MM#d) $  % (..!61+.. 99_l1g.FGD!'AF !j  ,QVV, , As$ (ID#sC=DcD5/C|| 5 8)*64 7; 6;+<==!v77J' ( & &)4A%,Q0@$%GN%1*KH:9JJy)JJy"A  '(% (!$ (N&,, ,,"!W5 s ==C155LI __yyT*smCL> !||#(;;s#3-aQ^^+-H-8}!qk**6215AACAFF?#E51 D|E{| !?%!GHH 996af 66  t9q=S$"?Q:a="?@AIE2JE5zA~S(<(<%<$);qQ]];;#(:aq"78:: U%7%7%=!>!BD||EJJ1(< % +0$2&'%&GGH$5$B$B %"$22DAq6A6656#7AEEG#7DAq)!S1'(!1(-dd )!S1jC7&*+&&)qvvay*@,0q%(1B,Ca,G&4n&6!)b')||+/D|"5z11#6u}*/g!'f!>!>).gU?u 0EqBc A ::b!,D 88F+"(q":E":!%gga"ff.N.N&O!PQR!SHO!P66;;s+;">356avqk6F6). *e(DE*% (D! 5&2E2D/34!61+44 !$))S,2B,C"DEE ( 0F yyT";ABaq1!1admmo%1BB,V4"jAw'#*)#'))** #<5!-u-U:<< My '  :/ P!- -+(  D#E?Lu$lFr0 r;r r r &rr#7r( m m - m:9m: nn&o ? o 

?@AB|sdgfSjddrM|}t|}|Dcic]}||j|z}}g}t|D cic]\}} | | c} }Bt|D].\} } |d| D]!} || || zs|j | | f#0||f} t | }t |dkDrg}d}|D]l}t}|D] }|||z} t|Bfd}dd<t||fi\}}|r|xr|}t|ts|g}|j |ng}t|D]#}|j td|D%||fSg}t}g}g}g}d}jd d}jd dx}}t|D]\}} |jt| |t!| g|\}}!|!|vr|rt#| d |!gd |!k(}|!|z } | j%d } |r|j | v| j&|d di}"|"|j |"|j | |rt)d |Drt |t |}#} t+| |#dz}$t|D]6\}}"|"j-D]\}%}& |%j/d}|&|$||f< 8jddrt3|$g|i}nt5|$g|i}|r|gng}|r|rt|d j7}ng}nd}t |t |kDrJtj8|D'cgc]}'|'jc}'}(tt;|(j=|}(t})g}t?|(tAt |(t |D]}* tC|g|*}+|+rtt|+D]f-d},-D]@|)stE@fd|)Dsd},|,r)|)j|*|j tttG|*-h|)r t|)}ns|jK|D cgc]} | jMc} nE tC|g|}|r6|}t|D-cgc] }-tttG||-"}}-|xsig}|rd}d?fd >t|?tO}.t;|>fdD]}/g}0g}1d}2|D]-t})|/jQ-}3|r9-r7tS|.|.|3d}4|4&|4r|0j -n|1j -Z>|3d}5|5s-r|0j -|5D]}6 tU|3|6fi}7|7D]A|)rtEAfd|)Dr-jW}8-jYD]\}9}:|:jQ|6A|8|9<A|8|6<t|8jY};|0D]T}t |t |;ks|jYD9:chc]\}9}:|9|:j[|8f}<}9}:|<|;z rT|0j |8d}2|)j]|6 |2rtId|3z|0}|1D]}4|4|vs|j_|4|sdgfSta|}=jd|=r$|D]--D]}9tc-|9-|9<dd<|r%|D--cgc]-tE-fd|Ds-}}-|r'|s%|D--cgc]-tE-fd|Ds-}}-|D-cgc]}-|-s|- }}-||fScc}wcc} }w#t0$r |& |$||#f<YwxYwcc}'w#tH$rYwxYwcc} wcc}-w#tH$r9|jK|D cgc]} | jMncc} wc} g}Y/wxYw#tH$rYwxYwcc}:}9wcc}-wcc}-wcc}-w)zreturn ``(linear, solution)`` where ``linear`` is True if the system was linear, else False; ``solution`` is a list of dictionaries giving solutions for the symbols F_splitTNrnc|Srr)r sym_indicess rrz_solve_system..s +a.rr'c3JK|]}|jD]}|ywr)ru)rsditems rrz _solve_system.. s/!," " !,"&!,!,s!#manualrr extensionc34K|]}|jywr) is_linear)rrs rrz _solve_system..,s*qq{{*rc3:K|]}|jvywrr)rssr1s rrz _solve_system..Ts"5._ok_syms..key}sqYYs^:"#**ajj!**!EJ!#!5!5J"$))+s:?/CS_!UJ!%5c%:$<<._ok_symsvs,%'B  =BC(Irc&t|Srr)rrs rrz_solve_system..sC ,<rr)rHc3:K|]}|jvywrr)rrrs rrz _solve_system..s(PBs/?/?)?(Przcould not solve %sr>c38K|]}t|fiywrrrs rrz _solve_system..s=1x1..=rc3<K|]}t|fiduyw)FNr)rrrrs rrz _solve_system..s"GAx1..%7Gs)F)2r/rrr0rtr^rrrErrrqrlrrvrr_invertrrrr:rQtermsindexrpminsolve_linear_systemsolve_linear_systemrr-r!rrcminrhrrBr4r8rrrorrcopyrur?rremoverr>)CexprsrxrVsymssetrexprsymsrr{rre1e2Gsubexprssubsolsrcsubexprsubsyms_linearsubsolsolssoldictspolysrfailedr solved_symsrrrjrmrrrmatrixmonomcoeffrfreersymsresr.rrr newresult bad_resultshiteq2r~ok_symsr|rrnewrriseti_items_updateddefault_simplifyrrrrrsC ` ` @@@@@rrErEs by yy4 g,9>?AAq~~//?? ,5g,>?&!SsAv? u% 'EArBQi 'B<(2,.HHb"X& ' ' qD'* x=1 GF# '% +Ax{*G+ 0HI"'h"/"JE"J#/F!&$/$XFv& 'D#W- - D!,!,,- -4<  E 5D F FK F YYx 'F '400I% 1 LG,-q#7#1 <%aQC03q8 E   q !  MM!  qyy'2T2   LL  MM! #& *E* *u:s7|qA1a!e_F$U+ .4$(JJL.LE5.!KKN',q!t . .yyu-/JJEJ,VGgGG!'fXRF"&vay~~'7"8K"$KF7|c%j("su{{U$CQ^^$CDGD$5$5g$>?@#D#c$iU*DED/==%(X L',*+!4B',5<5:5<2<04 !4 (,$)LL$6$*MM$tCaL7I2J$K L $"&u+KMM">1199;">?%.u?w?F&- KNv;!Wa$tC Q,?'@"A!W!W ^tF   (G  G&"<=B )BIKC> )ggajQ AsD9A}%,,Q/'..q1 #3T2!((+ !A!&sA77 $3 S(P%(P%P$ vvx$%GGI5DAq&'ffQnDG5#&Q"4::<0!* 3A"1vD 1UVU\U\U^2_TQPQAqzz$7G3H2_2_'6'=%* 3&,,T2+3,CIIaL?!@-.BS.HIIs> )v#$)AF{ a()AB )H byF| yy-. &A &!~! & &"j#?===?? V#IGGGII %A1a %F % 6>{@?H&.(-vq!t .&%D(/ #? "X*%MM">1199;">">?"$K%H/! !&3`J?I&s^ ^^1^7#%^< ^<^<%A^<_ $_%_&_, ` `+5`1`6`; `;^43^4< _ _ _`.` `` `( '`( c t|tr1|rttd|z|j}|j }d}||z }|j \}}|s tjtjfS|j}|s|}n|D cgc]} | jr| } } | r[t| dk(r| d} t|dk(r d|d|dd} nd|dt|d} ttd | d | d |j|}|j|}|s tjtjfSt!t} |j#t$D],} | j|z}|D]}| |j'| .d }t)|t* D]Rt| tr%| D cic]} | | j-c} | <|j/| }|j1j}sp|rt3fd|Ds||k(sd}tj4urnjvsdz |j/dz| t7||}t3fd|Drj#t8Dcgc]*}|j:j<r||j-f,}}t?j/|fcS|r tjtjfS|jr tjtjfS||fScc} wcc} wcc}w)a Return a tuple derived from ``f = lhs - rhs`` that is one of the following: ``(0, 1)``, ``(0, 0)``, ``(symbol, solution)``, ``(n, d)``. Explanation =========== ``(0, 1)`` meaning that ``f`` is independent of the symbols in *symbols* that are not in *exclude*. ``(0, 0)`` meaning that there is no solution to the equation amongst the symbols given. If the first element of the tuple is not zero, then the function is guaranteed to be dependent on a symbol in *symbols*. ``(symbol, solution)`` where symbol appears linearly in the numerator of ``f``, is in *symbols* (if given), and is not in *exclude* (if given). No simplification is done to ``f`` other than a ``mul=True`` expansion, so the solution will correspond strictly to a unique solution. ``(n, d)`` where ``n`` and ``d`` are the numerator and denominator of ``f`` when the numerator was not linear in any symbol of interest; ``n`` will never be a symbol unless a solution for that symbol was found (in which case the second element is the solution, not the denominator). Examples ======== >>> from sympy import cancel, Pow ``f`` is independent of the symbols in *symbols* that are not in *exclude*: >>> from sympy import cos, sin, solve_linear >>> from sympy.abc import x, y, z >>> eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0 >>> solve_linear(eq) (0, 1) >>> eq = cos(x)**2 + sin(x)**2 # = 1 >>> solve_linear(eq) (0, 1) >>> solve_linear(x, exclude=[x]) (0, 1) The variable ``x`` appears as a linear variable in each of the following: >>> solve_linear(x + y**2) (x, -y**2) >>> solve_linear(1/x - y**2) (x, y**(-2)) When not linear in ``x`` or ``y`` then the numerator and denominator are returned: >>> solve_linear(x**2/y**2 - 3) (x**2 - 3*y**2, y**2) If the numerator of the expression is a symbol, then ``(0, 0)`` is returned if the solution for that symbol would have set any denominator to 0: >>> eq = 1/(1/x - 2) >>> eq.as_numer_denom() (x, 1 - 2*x) >>> solve_linear(eq) (0, 0) But automatic rewriting may cause a symbol in the denominator to appear in the numerator so a solution will be returned: >>> (1/x)**-1 x >>> solve_linear((1/x)**-1) (x, 0) Use an unevaluated expression to avoid this: >>> solve_linear(Pow(1/x, -1, evaluate=False)) (0, 0) If ``x`` is allowed to cancel in the following expression, then it appears to be linear in ``x``, but this sort of cancellation is not done by ``solve_linear`` so the solution will always satisfy the original expression without causing a division by zero error. >>> eq = x**2*(1/x - z**2/x) >>> solve_linear(cancel(eq)) (x, 0) >>> solve_linear(eq) (x**2*(1 - z**2), x) A list of symbols for which a solution is desired may be given: >>> solve_linear(x + y + z, symbols=[y]) (y, -x - z) A list of symbols to ignore may also be given: >>> solve_linear(x + y + z, exclude=[x]) (y, -x - z) (A solution for ``y`` is obtained because it is the first variable from the canonically sorted list of symbols that had a linear solution.) z< If lhs is an Equality, rhs must be 0 but was %sNrnrzsolve(r#)z, *z8 solve_linear only handles symbols, not z=. To isolate non-symbols use solve, e.g. >>> z# <<<. Tr'c3@K|]}j|ywr)diff)rr| dnewn_dxis rrzsolve_linear..s)J)..*;)JFrc3BK|]}t|idduyw)TrNr)rdivirs rrzsolve_linear..s+* $BR$?4G*) rrrrpr\rrrrr9rrr3rrqr differencerjrrrtrr"doitrorrrrr<functionrr )rrrxrrrrrr r|badegderivsdercsymrsall_zeronewnr{ireprr!rs @@@rrrs4V#r Z)?AD)EFG Ggggg D sB   DAq vvquu} >>D !5Qq55 3x1}!f7|q (*GAJ7!*,T'];Z%()-./ /##G,  )G vvquu}  Fwwz""') "A 1I  S ! "" HW"23" fRj$ '5;BZ@c#sxxz/@F2JvvfRj!IIbM %% dc)JT)J&JdV]oHAEE!/// \499R#34<'G4D*$(**4688H3E2aJJ00M2D2$BGGDM2Br6M1"2vvquu}{{vvqvv~ a4Kq6<A"2sM(MM"9/M'c  |jdd}t|g|i|}|r td|jDr|S|rt|g|}d}i}||||rt d|jDd}|j } t ttt|  t| dk7rtj| <nOt| d d s7t fd |jDstj| <n| <||||r|St|} t!|g|dd i} t| jD cgc] } | d k7s |  c} } t#| dz dd D]d}t%d|d}t't#| |D]3}t)|Dcgc]}|j+|j,c}|j+d j,gzj,}t|g|Dcgc]}|| c}}|s}td|jDr|Dcgc]}||tjf}}|j/D]\}}|j1|||<|D]A}||vs|j3||vrtj||</tj||<C|}n|| S|} g| Scc} wcc}wcc}wcc}w)a! Find a particular solution to a linear system. Explanation =========== In particular, try to find a solution with the minimal possible number of non-zero variables using a naive algorithm with exponential complexity. If ``quick=True``, a heuristic is used. rFc3&K|] }|dk( ywrNrrrs rrz)minsolve_linear_system..s1Q!V1rcg}|jD]B\}}|j|||<||jr*|j|||||<D|D]}||=yr)rurorrt) determinedrbdeleterrs rrz&minsolve_linear_system..updatesqF ( 01ffZ0 {//MM!$$,QKJqM  0  QK rc3 K|]}|ywrr)rrs rrz)minsolve_linear_system..s+1Q+s cBt|jt|fSr)rrr"rs rrz(minsolve_linear_system..s3q~~#68H8K"Lrr'rn)rrc3BK|]}|jywr)ro)rrrrs rrz)minsolve_linear_system..s&J!qvva~&Jr"Trz minsolve: %sNc3&K|] }|dk( ywr0rr1s rrz)minsolve_linear_system..s 234A5zQ ! 1 a%033&Jqxxz&J#J$%EEJqM$'JqM :q ! L(F'FF W^^-8a!8 9rAvq"% A >1 %G(q15 A1vzz!}AVZZPR^EUEUDVVWYY'NH/Mq /MNS < <<9ABAWQZ/BDB ! ,1 vvd|!,&0a<&}}S1X=)*#)*# 0  G G) *-9 B/MBs+ K;6K;"L LL c|jdt|dzk(sJt|t|dzz}t ||\}}t ||d}|)|j Dcic]\}}||k7s ||}}}|Scc}}w)a9 Solve system of $N$ linear equations with $M$ variables, which means both under- and overdetermined systems are supported. Explanation =========== The possible number of solutions is zero, one, or infinite. Respectively, this procedure will return None or a dictionary with solutions. In the case of underdetermined systems, all arbitrary parameters are skipped. This may cause a situation in which an empty dictionary is returned. In that case, all symbols can be assigned arbitrary values. Input to this function is a $N\times M + 1$ matrix, which means it has to be in augmented form. If you prefer to enter $N$ equations and $M$ unknowns then use ``solve(Neqs, *Msymbols)`` instead. Note: a local copy of the matrix is made by this routine so the matrix that is passed will not be modified. The algorithm used here is fraction-free Gaussian elimination, which results, after elimination, in an upper-triangular matrix. Then solutions are found using back-substitution. This approach is more efficient and compact than the Gauss-Jordan method. Examples ======== >>> from sympy import Matrix, solve_linear_system >>> from sympy.abc import x, y Solve the following system:: x + 4 y == 2 -2 x + y == 14 >>> system = Matrix(( (1, 4, 2), (-2, 1, 14))) >>> solve_linear_system(system, x, y) {x: -6, y: 2} A degenerate system returns an empty dictionary: >>> system = Matrix(( (0,0,0), (0,0,0) )) >>> solve_linear_system(system, x, y) {} rn)rF)_raw)shaperrqrPrVrWru)r>rxrrwringrrrs rrrs^ <<?c'lQ. .. . vw// 0C!#w/IC T .C '*yy{A83cSjs3wAA JBs - B;Bc8|rtd|Ds tdt|tr|j|j z }n|}t |}t|jdd}|j}|t|z}|s|jddrgifSgS|sN|j|ddi\}} | j} | |jz}|s| t|z }|sEtg}n9t|d k(rt|dr|d}t!|g|\} } } | d}| }t|j"|j%d hz }t|t'fd |Dryt!|gt)|\} }} | d}t)t+||d j-}t/||fi|}|jd dxs|jdd}t1|t2us|st|d k7r|S|dS)az Solve a system of equations in $k$ parameters that is formed by matching coefficients in variables ``coeffs`` that are on factors dependent on the remaining variables (or those given explicitly by ``syms``. Explanation =========== The result of this function is a dictionary with symbolic values of those parameters with respect to coefficients in $q$ -- empty if there is no solution or coefficients do not appear in the equation -- else None (if the system was not recognized). If there is more than one solution, the solutions are passed as a list. The output can be modified using the same semantics as for `solve` since the flags that are passed are sent directly to `solve` so, for example the flag ``dict=True`` will always return a list of solutions as dictionaries. This function accepts both Equality and Expr class instances. The solving process is most efficient when symbols are specified in addition to parameters to be determined, but an attempt to determine them (if absent) will be made. If an expected solution is not obtained (and symbols were not specified) try specifying them. Examples ======== >>> from sympy import Eq, solve_undetermined_coeffs >>> from sympy.abc import a, b, c, h, p, k, x, y >>> solve_undetermined_coeffs(Eq(a*x + a + b, x/2), [a, b], x) {a: 1/2, b: -1/2} >>> solve_undetermined_coeffs(a - 2, [a]) {a: 2} The equation can be nonlinear in the symbols: >>> X, Y, Z = y, x**y, y*x**y >>> eq = a*X + b*Y + c*Z - X - 2*Y - 3*Z >>> coeffs = a, b, c >>> syms = x, y >>> solve_undetermined_coeffs(eq, coeffs, syms) {a: 1, b: 2, c: 3} And the system can be nonlinear in coefficients, too, but if there is only a single solution, it will be returned as a dictionary: >>> eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p >>> solve_undetermined_coeffs(eq, (h, p, k), x) {h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)} Multiple solutions are always returned in a list: >>> solve_undetermined_coeffs(a**2*x + b - x, [a, b], x) [{a: -1, b: 0}, {a: 1, b: 0}] Using flag ``dict=True`` (in keeping with semantics in :func:`~.solve`) will force the result to always be a list with any solutions as elements in that list. >>> solve_undetermined_coeffs(a*x - 2*x, [a], dict=True) [{a: 2}] c34K|]}|jywr)r3r*s rrz,solve_undetermined_coeffs..s s711;;7rzmust provide symbols for coeffsrTrrNas_Addrnc3@K|]}|jywr) has_xfree)rrmcsets rrz,solve_undetermined_coeffs.. s +1;;t  +rFrr)r:rprrrrrrSrrrrrvrrrraras_coefficients_dictrrrqr?rrjr1r)equcoeffsrrrceqxeqr r`radfreerr|rrr>rsettingsrPs @rrlrl2 sB s777:;;#r WWsww   *C 3%%'*d ;C   D CK F  99UD1Bx9r9  &3%%v;d;S  s'''3v;&DG9D t9>htAw/7D#SE401ad 's''.335 6! F  )5 )Dyy&@%))E4*@H DzTXTa 7Nrc6|j|jdz k7r td|d|jd|jf}|dd|jdz df}|j|}i}t |jD]}||df|||<|S)a Solves the augmented matrix system using ``LUsolve`` and returns a dictionary in which solutions are keyed to the symbols of *syms* as ordered. Explanation =========== The matrix must be invertible. Examples ======== >>> from sympy import Matrix, solve_linear_system_LU >>> from sympy.abc import x, y, z >>> solve_linear_system_LU(Matrix([ ... [1, 2, 0, 1], ... [3, 2, 2, 1], ... [2, 0, 0, 1]]), [x, y, z]) {x: 1/2, y: 1/4, z: -1/2} See Also ======== LUsolve rnz#Rows should be equal to columns - 1Nr)rowscolsrpLUsolver;)r rAr~rrr{s rsolve_linear_system_LUr] s8{{fkkAo%>??| |\fkk\)*Aq&++/""#A 99Q. s6'(qAw1q5># MM)A$5$5a$;< =(?a!Q$ (?#@@FF#6(?sAA< A7  A<)rYrr;)r`rs` rriri sV AAvwqw44006,1!H66 6rctd|Dr7|jdkrtd|Dr t|St |S|r|j |S|j S)a Return ``det(M)`` assuming that either there are lots of zeros or the size of the matrix is small. If this assumption is not met, then the normal Matrix.det function will be used with method = ``method``. See Also ======== det_minor det_perm c3FK|]}|jtywrrrr*s rrzdet_quick.." s $Q155= $!c3FK|]}|jtywrrmr*s rrzdet_quick..# s7aeeFm7rn)method)rrYr:rfridet)r`rqs r det_quickrs s\ $! $$ 66A:#7Q77A; |'-quuFu#:1557:rctd|Dstd|Dsd}nd}n|jS|j}||}|tj k(r t dt|}d}t|D]?}| x}}t|D]*}||j||} || z|z |||f<| },A|S)zzReturn the inverse of ``M``, assuming that either there are lots of zeros or the size of the matrix is small. c34K|]}|jywrrr*s rrzinv_quick../ s&qq{{&rc34K|]}|jywrrvr*s rrzinv_quick..0 s*11;;*rct|Sr)rfrs rrzinv_quick..1 s HQKrct|Sr)rirys rrzinv_quick..3 s IaLrzMatrix det == 0; not invertibler) r:rrrYrr9rOrQr;rj) r`rrrrrets1r{r|r r s r inv_quickr}* s &A& &***'C(Cuuw A AAAFF{&'HII (C B 1X Bq AQ&&q!,-B"QC1IA  JrcPt|tjt|z fSr)r/rPirs rrrG sDGQTTDG^,rcVt|dtjzt|z fSNr)r.rrrs rrrH s DGQqttVd1g-.rc Ht||fi|Dcgc]}|| c}Scc}w)z?return list of scalar values for the solution of e for symbol s)rD)rr|rr{s rrrL s& A// 0QAaD 00 0s c |d|vrg|d<||dvry|dj|t||\}}||k(r|gS |jrtt ||z }|j r t ||fi|S|rjt||jdd}|jt|jtk7r!t|tr&t |jdt|z |fi|St||z |fi|S|jr|jj r||z |k7rt ||z |fi|S||jj"vr*t |j$|d|jz zz |fi|St'd|j"Drt(|sGt |j$|fi|}|Dcgc]$}|jj+||dk7s#|&c}S|j$j-|s|j$dk(r|dk7rt |j|fi|SgS|j$|j/dk(r,t |j|j/dz |fi|}nMtt|j$|jztt|z }t ||fi|}d } t1tt3|tt3|j$z } t5t7| d} t9| \} } t;|j$| z|| zz dk(r\|Dcgc](}| |jj+||| r'|*}}|j=t |j| z |fi|t?tA|Sg}|jt|j$zt|z } | ||z k7r |j=t | |fi|g}|dk(rz|j=t |j|fi||j=t |j$dz |fi||j=t |j$dz|fi|n|jBrd tEt3|jFDD]} tI|jF| \}}|stEt3|jJD]}||z|jJk(stM| |}|j=t |j$|z |fi||j=t |j$|z|fi||j=t |j|z |fi|n|jNr|j$j/\}}||jzjQ\} } tS|j/\}}t |j$|z |fi|Dcgc] }tS|}}|j=t |j|z |fi|Dcgc] }tS|c}|| zdk7r(|j=t || z||| zzz |fi||D]F}tU|||}|!|j+||jWd}|s6|j|Ht?tA|S|jXrt[|jdk(r|j\t^vr^g}t_ta||D].}|j=t |jd|z |fi|0t?tA|S|j\tbk(r)t |jd|t|zz |fi|S|jet}tg|}||k7rt ||z |fi|S |jid dr|jkt}tm|Dchc]7}|jktnD]}|j$|k(r |j9c}}xsdh}|dk7rx||z}tqd }|j+||}|js|sEt ||fi|}t ||z |}|Dcgc]}|D]}|j+||c}}Stu|jw|} tA}!| D]}"t|"ttfs)|"jr/|"j$txjzk(r|!j}|"T|"jsat t|"}#|#js||#jj"vs|!j}|"tt|j+tt?t|!dgt[|!z}$tt|$d ||$z z}t||\}}|j-|r |jw}%tu|%|} ||z }&t|&|| }'t|'D]p\} }t1|}(|(|k7s|(j|jks9tU|&||(}|!|&j+||(jWd}|sl|(|'| <r|'S|jiddrd|d<t7||z \}+},|txjk(rgS|,jD] \}}||k(s n|}|+j-|r- t |+|fi|}|Dcgc]}|j+|,c}S ycc}wcc}w#t($rYwxYwcc}wcc}w#t($rYwxYwcc}}wcc}}w#t($rt[| dk(r t||z g| })|)t(|)\} }}d|d <t| |z |fi|}*|*rHt ||fi|}t?|*Dchc]}|D]}|j+||ncc}}wc}}cYSn#t($rYnwxYw YwxYwcc}w#t($rYywxYw)a Helper for ``_solve`` that solves a transcendental equation with respect to the given symbol. Various equations containing powers and logarithms, can be solved. There is currently no guarantee that all solutions will be returned or that a real solution will be favored over a complex one. Either a list of potential solutions will be returned or None will be returned (in the case that no method was known to get a solution for the equation). All other errors (like the inability to cast an expression as a Poly) are unhandled. Examples ======== >>> from sympy import log, ordered >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy.abc import x >>> list(ordered(tsolve(3**(2*x + 5) - 4, x))) [-5/2 + log(2)/log(3), (-5*log(3)/2 + log(2) + I*pi)/log(3)] >>> tsolve(log(x) + 2*x, x) [LambertW(2)/2] tsolve_sawNrT)rrrnc34K|]}|jywr)is_Dummy)rr[s rrz_tsolve.. s8!1::8rct}t||z ||}|)t|t|k7ry|j|}|S)NF)rrrCequals)expr1expr2rrs requalz_tsolve..equal sJA!%!)Q6Bz$U+y/??#(#\\%0Irc3,K|] }|dk7s |ywrrr*s rrz_tsolve.. sHAaaHs  bivariatez bivariate-cov)deeprF)IrtrrrTrBr@rrErvcountr(rrrr)rrrrrrr4rorr{rCrr>rArGrr8rqrrr=rrr|r is_irrationalrrFrrrrrAmulti_inversesr1r*rrNr/rrrrr_filtered_gensrrExp1rrr rrB_solve_lambertr0 count_opsbivariate_typerru)-rrrrrrsol_baser|rre_ratrrlogformrrr[rb_le_lr~r{rXrrlogsr spowrrueqrrm up_or_loggigisimpeq_downr_eqrnsgpu inversionposrs- rrrQ s 85  l U<   l""2&r3HC czu A ::ys+,Axxq#///s%))GT*BC773<399S>1!!S)&qvvay3s8';SJEJJ"1s7C9599 ZZww!!9?"39c;U;;#''...sxx##'' *::CI5II8s'7'788))#388S:E:#+Iasww||C/Cq/HII88<<$88q==@AX7377C959M2M88s033!#''COO,=a,@"@#OOCCM#''12SS]BA!!S2E2C "#c#h-CM0B"BC q!121#((A+Q./14&)Tsww||C7KU1S1TCTJJwswwEuEFCH~%''#chh-/#c(:cCi' 77C#A5#AB !8LL#!?!?@LLAs!De!DELLAs!De!DE__H#cee*)=H Q*355!41 $!)#cee*!5QA !tcee|$,QN % WSXX\3-P%-P Q % WSXX\3-P%-P Q % WSWWq[#-O-O P Q Q&&"xx335HCK779DAq%c?668DAq5)'S 237HAKK a F FGHCI&X%sxx{SS\93H%HH++c"'" c>7S=#77 7   yyd# xx}  q!''#, Q# UU U  &#$#' 19T Ao&A''!Q-C<<$c1..a!eS).1?3?aq! ? ?? 2::< -E  &B"sCj)biiBGGqvvQ[[]#B%c33:!$#r!2!9!9!!-n>1o"4Ao";o"=D"o"(oo >o" 8o"o Do"&Do"4o)o"/oA.o"0&o"Bo"+;o"'4o"!o>$2o>o>r/!r*9r/> o" oo"o o"" o/.o/>r'A r! r rr'r' rr'rr'&r'*r// r;:r;Frc d|vrttdd|vr$ddl}|jd|j_|}ddlm}t|dk(r^|d}|d}|d }t|rt|rt|t|k7rtd t|t|fzt|d k(r"|d}d}|d}t|rGtd t|d krtd t|ztd t|z|jddg}t|r`t|}t|D]2\} } t| ts| j | j"z || <4t%|j&}t|r t|}t|t$st|tr|j |j"z }n|j(r td|j*} || j-j}t| dk(r || vs|d| vsttdt/|||}t1t3||fi|} |r|| igS| St||j4kDrt7td|jdd} | rt9dt9||j;|}| rt9dt9|t/||j&|}t/|||}t3||fd|i|} |r*|t=|| Dcgc] }t1|c}gSt%| Scc}w)a Solve a nonlinear equation system numerically: ``nsolve(f, [args,] x0, modules=['mpmath'], **kwargs)``. Explanation =========== ``f`` is a vector function of symbolic expressions representing the system. *args* are the variables. If there is only one variable, this argument can be omitted. ``x0`` is a starting vector close to a solution. Use the modules keyword to specify which modules should be used to evaluate the function and the Jacobian matrix. Make sure to use a module that supports matrices. For more information on the syntax, please see the docstring of ``lambdify``. If the keyword arguments contain ``dict=True`` (default is False) ``nsolve`` will return a list (perhaps empty) of solution mappings. This might be especially useful if you want to use ``nsolve`` as a fallback to solve since using the dict argument for both methods produces return values of consistent type structure. Please note: to keep this consistent with ``solve``, the solution will be returned in a list even though ``nsolve`` (currently at least) only finds one solution at a time. Overdetermined systems are supported. Examples ======== >>> from sympy import Symbol, nsolve >>> import mpmath >>> mpmath.mp.dps = 15 >>> x1 = Symbol('x1') >>> x2 = Symbol('x2') >>> f1 = 3 * x1**2 - 2 * x2**2 - 1 >>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8 >>> print(nsolve((f1, f2), (x1, x2), (-1, 1))) Matrix([[-1.19287309935246], [1.27844411169911]]) For one-dimensional functions the syntax is simplified: >>> from sympy import sin, nsolve >>> from sympy.abc import x >>> nsolve(sin(x), x, 2) 3.14159265358979 >>> nsolve(sin(x), 2) 3.14159265358979 To solve with higher precision than the default, use the prec argument: >>> from sympy import cos >>> nsolve(cos(x) - x, 1) 0.739085133215161 >>> nsolve(cos(x) - x, 1, prec=50) 0.73908513321516064165531208767387340401341175890076 >>> cos(_) 0.73908513321516064165531208767387340401341175890076 To solve for complex roots of real functions, a nonreal initial point must be specified: >>> from sympy import I >>> nsolve(x**2 + 2, I) 1.4142135623731*I ``mpmath.findroot`` is used and you can find their more extensive documentation, especially concerning keyword parameters and available solvers. Note, however, that functions which are very steep near the root, the verification of the solution may fail. In this case you should use the flag ``verify=False`` and independently verify the solution. >>> from sympy import cos, cosh >>> f = cos(x)*cosh(x) - 1 >>> nsolve(f, 3.14*100) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (1.39267e+230 > 2.1684e-19) >>> ans = nsolve(f, 3.14*100, verify=False); ans 312.588469032184 >>> f.subs(x, ans).n(2) 2.1e+121 >>> (f/f.diff(x)).subs(x, ans).n(2) 7.4e-15 One might safely skip the verification if bounds of the root are known and a bisection method is used: >>> bounds = lambda i: (3.14*i, 3.14*(i + 1)) >>> nsolve(f, bounds(100), solver='bisect', verify=False) 315.730061685774 Alternatively, a function may be better behaved when the denominator is ignored. Since this is not always the case, however, the decision of what function to use is left to the discretion of the user. >>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100 >>> nsolve(eq, 0.46) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19) Try another starting point or tweak arguments. >>> nsolve(eq.as_numer_denom()[0], 0.46) 0.46792545969349058 rqz Keyword "method" should not be used in this context. When using some mpmath solvers directly, the keyword "method" is used, but when using nsolve (and findroot) the keyword to use is "solver".precrNrrnrz0nsolve expected exactly %i guess vectors, got %iz"nsolve expected 3 arguments, got 2z,nsolve expected at least 2 arguments, got %iz+nsolve expected at most 3 arguments, got %imodulesmpmathz!nsolve cannot accept inequalitieszB expected a one-dimensional and numerical functionz9 need at least as many equations as variablesverboseFzf(x):zJ(x):J)rpr\rr/mpdpsbuiltinsrrrarrvrqr0rrrrrrPr=rrrr[r#rgrZr4printjacobianrB)rrkwargsrrdrfargsx0rr{rrrrrrs rnsolverX sL^6%   6* G 4yA~ GQ !W E?x|2w#e*$ R#&u:s2w"7!899 Ta G !W A;@A A TQFd)$% %Ed)$% %jjXJ/G{ Gq\ 'EAr"b!vv! ' 1IKK| "X a a  A __?@ @~~ =IIKOO%ED QETMU1X5EZ)EFG G UAw ' HQ-f- . AJ<  5zAFF!*.<#=> >jjE*G g a 5A g aW%A7#AB&!&v&ASq 9 9:;<< !9!:s M4c  t|}|jr|j|j}|j}|s|}|t |zs|t j fSt|jdd}|}t j } |} |j|\}} |jr|jrn#| }||z}n|t jurn| }||z}N|jri} |jD]5} | j|\} } | j| gj| 7td| j!Drbg}| j#D]E\} } t%| dkDr|jt'| | z/|j| d| zGt'|}|jr|st%|jdk(r|j(|st+|j\} }| j|\}}|j|\}}td||fDr|j-\}}|j-\}}||k(r2|j/|!t1t3||z }|}| |z }n#||z }t1||z }||k7r |}| |z }n|| k(rt5|t6r|j|jk(rt%|jt%|jcxk(rdk(r#nn |jd|jdz }n}t%|jt%|jk(r t9dt;d |j<r0td |jDrt1t3|}|j>rMtA|d rN|jC>t%|jdk(r&|jC|}|jd}nt5|tDr6|j\}}dtG|tI|dz|dzz|zz z}n|j|jk(rt%|jt%|jcxk(rdk(r"nn|jd}|jd}nAt%|jt%|jk(r t9dt;d |r;|jJr/|jLjNr|jLdkr d|z }d|z }|jJr|jLjNr|sR|jLjNsZt%|dkDrLt%|jPjt |zdkDr|d|jLz z}|jP}||k(r ||fSe) aY Return tuple (i, d) where ``i`` is independent of *symbols* and ``d`` contains symbols. Explanation =========== ``i`` and ``d`` are obtained after recursively using algebraic inversion until an uninvertible ``d`` remains. If there are no free symbols then ``d`` will be zero. Some (but not necessarily all) solutions to the expression ``i - d`` will be related to the solutions of the original expression. Examples ======== >>> from sympy.solvers.solvers import _invert as invert >>> from sympy import sqrt, cos >>> from sympy.abc import x, y >>> invert(x - 3) (3, x) >>> invert(3) (3, 0) >>> invert(2*cos(x) - 1) (1/2, cos(x)) >>> invert(sqrt(x) - 3) (3, sqrt(x)) >>> invert(sqrt(x) + y, x) (-y, sqrt(x)) >>> invert(sqrt(x) + y, y) (-sqrt(x), y) >>> invert(sqrt(x) + y, x, y) (0, sqrt(x) + y) If there is more than one symbol in a power's base and the exponent is not an Integer, then the principal root will be used for the inversion: >>> invert(sqrt(x + y) - 2) (4, x + y) >>> invert(sqrt(x + y) + 2) # note +2 instead of -2 (4, x + y) If the exponent is an Integer, setting ``integer_power`` to True will force the principal root to be selected: >>> invert(x**2 - 4, integer_power=True) (2, x) integer_powerFc38K|]}t|dkDywrrr1s rrz_invert.. s6!3q6A:6rrnrrc32K|]}t|ywrrr*s rrz_invert.. s/6!9/r&z(equal function with more than 1 argumentz'function with different numbers of argsc32K|]}t|ywrr)rrs rrz_invert.. su ', ::EXX 2'q''11  B'..q1 26u||~66!KKM,DAq1vz CGAI. AaDF+ , 4j ::cc#((mq&8%C%%w/388$DAq%Q%%w/FB%Q%%w/FB/r2h// " 0  " 0 V#(@(@(G(O")BrE"23CC#b&CR%C"2b5>Ds{"!c"fsb(+2770B277|s277|8q8 ggaj2771:5RWWRWW52FHH)EGGZZC<388<<)C.)C ??sI&3;;=+DSXXZ[I[$ckkmC(hhqkC'xx1QQTAqD[ 1A 5677SXX%sxx=CM6Q6((1+C((1+C]c#((m3.BDD%ACC 3::#''"4"41C%CC%C :: GG  83773E3EG q S)>)>W)M%NQR%R#'' "C((C #:  8O{ rc FGHIJKLdddLILfd}d}dHHfd}|jd|}t|tr|j|jz }nt|t syt gdd d jDcgc]\}}|j||c}}\I}} tt|d d }|jd }t|d }|jrytxs |j|j} | j D cgc] } || s | } } | sy|j| } | yt#fd| DryHfd} | | \}}}t%dd }t}|D] }|j'|jz"|k7r|t)t+|t-t/|}dgiKt1j2| j5}|D]}||rXt|jj j7|}t9t |Dcgc]}|| c}}nd}Kj|gj;|t1Kj=d}Kj?Dcgc] }t1K|c}KtAtCtAtEKKd}tG|}t/Kdk(r'Kd jHr|dkDsKd |z| |zz }d }nt/Kdk(r'Kd jHrtAKd jJKt/|dk(r|j=}t/dkDr |j}n}tAtE|d } tM||z|z |fiL}|stN| j5jQ|||zjQ||d }||||z|z ||ISt/Kdk(rV|sKd |zKd |zz }d }n-tS|djTsK\} }!|jWddr| |!} }!| | jx}"\}#}$}%| |!jx}&\}'}(})t-dD]}*|*r|&|"}&}"|!| }!} |&\}'}+})tY|'}'|'|)z},||)z|,z }-D]} tM|-|fiL}.|.stN| jQ||.d ||!z|'z z|z}/t[|/|}0|0r>|0\}}1|1r-|1\}2}3||2|-jQ|tM|3|fiLd n|||-n |/}|||-d }n|snnt/Kdk(rKDcgc]}| |jc}Jd GdFd}4Jd |4dk7rAJj;Jj=d Kj;Kj=d nKJd|4dk7r@Jj;Jj=dKj;Kj=dJd |4Jd|4cxk(rdk(rnnJdFJdFk7r"JdJd cJd <Jd<KdKd cKd <Kd<JdFJdFk(rKd dzKdKdz|zdzz}d }nJd|4dkrdDcgc] }t%|c}\}5}}-}6}7}8|-|6z |7dz|5dzzd|7dzz|8z|5dzz|dzzzd|7dzz|5dzz|-dzzz d|7dzz|5dzz|-dzz|6zzd|7dzz|5dzz|-z|6dzzz d|7dzz|5dzz|6dzzzd|7z|8dzz|5dzz|dzzzd|7z|8z|5dzz|dzz|-dzzzd|7z|8z|5dzz|dzz|-dzz|6zz d|7z|8z|5dzz|dzz|-z|6dzzzd|7z|8z|5dzz|dzz|6dzzz d|7z|5dzz|-dzzzd|7z|5dzz|-dzz|6zz d|7z|5dzz|-d zz|6dzzzd!|7z|5dzz|-dzz|6dzzz d|7z|5dzz|-dzz|6d zzzd|7z|5dzz|-z|6dzzz d|7z|5dzz|6dzzz|8dz|dzzzd|8dzz|dzz|-dzzz d|8dzz|dzz|-dzz|6zzd|8dzz|dzz|-z|6dzzz d|8dzz|dzz|6dzzzd|8z|dzz|-dzzzd|8z|dzz|-dzz|6zz d|8z|dzz|-d zz|6dzzzd!|8z|dzz|-dzz|6dzzz d|8z|dzz|-dzz|6d zzzd|8z|dzz|-z|6dzzz d|8z|dzz|6dzzz|-dzz d|-d"zz|6zzd#|-d$zz|6dzzz d%|-dzz|6dzzzd&|-dzz|6d zzz d&|-d zz|6dzzzd%|-dzz|6dzzz d#|-dzz|6d$zzzd|-z|6d"zzz |6dzzz}9FGJKfd'}:|:d \};}<|:d\}=}>Kd }?|}@|9j]t)t+|5|7||8|-|6f|;|<|=|>|?|@f}d }|stS|djTr|st/Kd k(st/Kd kr|d(}At/Kd k(rK\} }!}B}CA| |!|A|B|Cz }d }nNt/Kdk(rK\} }!}BA|!|B|A| |z }d }n$t/Kdk(rK\} }!| dzA|!|z }d }|r tG|n|}D| dz } |r|%t/K|k(rDD|k(r| dkDr tOd)|j'It/K| d t[|gi|}E|ErE\}I||I\}I|IfScc}}wcc} wcc}wcc}w#tN$rYwxYw#tN$r|*r tOdYwxYwcc}wcc}w)*a Remove radicals with symbolic arguments and return (eq, cov), None, or raise an error. Explanation =========== None is returned if there are no radicals to remove. NotImplementedError is raised if there are radicals and they cannot be removed or if the relationship between the original symbols and the change of variable needed to rewrite the system as a polynomial cannot be solved. Otherwise the tuple, ``(eq, cov)``, is returned where: *eq*, ``cov`` *eq* is an equation without radicals (in the symbol(s) of interest) whose solutions are a superset of the solutions to the original expression. *eq* might be rewritten in terms of a new variable; the relationship to the original variables is given by ``cov`` which is a list containing ``v`` and ``v**p - b`` where ``p`` is the power needed to clear the radical and ``b`` is the radical now expressed as a polynomial in the symbols of interest. For example, for sqrt(2 - x) the tuple would be ``(c, c**2 - 2 + x)``. The solutions of *eq* will contain solutions to the original equation (if there are any). *syms* An iterable of symbols which, if provided, will limit the focus of radical removal: only radicals with one or more of the symbols of interest will be cleared. All free symbols are used if *syms* is not set. *flags* are used internally for communication during recursive calls. Two options are also recognized: ``take``, when defined, is interpreted as a single-argument function that returns True if a given Pow should be handled. Radicals can be removed from an expression if: * All bases of the radicals are the same; a change of variables is done in this case. * If all radicals appear in one term of the expression. * There are only four terms with sqrt() factors or there are less than four terms having sqrt() factors. * There are only two terms with radicals. Examples ======== >>> from sympy.solvers.solvers import unrad >>> from sympy.abc import x >>> from sympy import sqrt, Rational, root >>> unrad(sqrt(x)*x**Rational(1, 3) + 2) (x**5 - 64, []) >>> unrad(sqrt(x) + root(x + 1, 3)) (-x**3 + x**2 + 2*x + 1, []) >>> eq = sqrt(x) + root(x, 3) - 2 >>> unrad(eq) (_p**3 + _p**2 - 2, [_p, _p**6 - x]) F)rr>c rN\}}t||j|dvr&||j|t||fidgddyt||gddy)N)rnrr)rUrrorr4)rroldpolderuflagss r_covzunrad.._cov( se JD$Aqz  #v-TYYtWQ-DV-DQ-GHIA))VCFrc|rO|\}}|t|ji}|j|}|j||j|g}tt |j ddd}|j rag}|jD]H}|jr|jr|j|j8|j|Jt|}ttj|}d}t|D]\} } | j!s| || <d} |r t|ddi}||fS)NrTr)clearFr)rnamer?r rrr@rrrrtrr rqrr0could_extract_minus_sign) rrrrreprrmargschangedr{rs r _canonicalzunrad.._canonical3 s- DAqeAFFm$CS!B::c?AJJsO4C(2#4#4#6q#9TJRV W 99DWW #;;88KK'KKN  #dBS]]2&'e$ DAq))+2a  e,e,B3wrc|jdjd}|jstjS|j S)Nrnr)r{r}rrrr|)powrss r_Qzunrad.._QU s: OO a - - / 2}}55Lss rctj|D],}|js|dk(r|jzs,yy)NrnTF)r rrr)rrrrs r_takezunrad.._take] sI==# C::#w!|$&  rrNr)rrrptT)radicalrrc3PK|]}|jjywr)r)r)rrmrs rrzunrad.. s *915599d  *s#&cd}t}t}|jD]H}|}|dk7s|j|t||}|j|jJ|||fSrv)rrrrr)rlcmradsrrmr|rs r_rads_bases_lcmzunrad.._rads_bases_lcm spu "A1AAv 3l !&&!  " UCrr) nonnegativerrnr_reversez&no successful change of variable foundrabcdAB ?r-<ro$T~c^t|}t||z t|fSr)r rS)r{r~BASESRADinfortermss r_tzunrad.._t&s:a.%fQik2Ca4HHHrc*|dz|dzzd|z|zzSrr)rr~s r_norm2zunrad.._norm25s!a4!Q$;1Q..rzCannot remove all radicals)/r,rrrrrrrrurBr rrrrrrrrrrrrBr;rrrrrrrtr/rrqrr!rIrrrr4ror(rrvr rr?)Mrrrrrrrrnwasrrrmrrrrrcovsymnewsymsrdradrr[commonr{r(othersrXdepthr~rrr0ri0_rads0_bases0lcm0i1_rads1_bases1lcm1reversert1rsrneweqtmpnewcovnewpnewcLCMrrr\rzzraaAAbbBBccddrr2r3 new_depthneqrrrrrrrsM ` @@@@@@@rrr sF% 0F  D    We ,E"b VVbff_ D ! rQ/5578:Ae&&q!,:NCs <D= >B   Q B " %B || t9 'D ::T!WU^3'+AwQ$DGT!W+1!9fQi(F1Ivay75>T!WU^3AVAY)>)G!(KKBB!WS\A%:B'CQa'C$Aq!Q1a%!Q$q!t)a1fQhq!tmAqD.@"@!Q$q!t AqD(#)+,QT6!Q$;q!t+;A+=#>@A!Q$q!t A aQRd@R#S!Q$q!t AqD(#)+,Q3q!t8AqD=A+=#>@B1Qq!t AqD@PQRTUQU@U#V1Qq!t AqD(A-a/#035Q$q&A+ad2B12DQT2I#J1Qq!t AqD(A- #.12!AqDA #>AC1QT !Q$q@P #Q 1QT !Q$q!t+ #, /1d1a4i1nQT.A #B EGqDAIaQRdNSTVWSWDW #X 1QT ! AqD( #) ,-Q3q!t8AqD= #9 <=a419 #E HIAvaQRd{STVWSWGW #X!Q$q!t AqD(*#+./q!tVAqD[]1a4-?#@CDAqD&A+aQRdBR#S!AqDA #&)+1QT !Q$q(8#9<>a419QT>!Q$;N#O1QT !Q$q!t+ #,/1d1a4i1nQT.A #BEGqDAIaKPQSTPTDT #U!AqDA  #&)*1 #-01Avax #8;=QT'!Q$, #GJLAqDQRTUQU #VAqDA  #&),AqDA  #69;1a41  #EHJ!Q$wqRSt| #T!AqD #!$%a4 #( )BI UFBUFB )BBT#Aq!Q*RRR0+2&34BB3{%%vK1$F a/v;!#%+NBBB&R.8BB[A%!'JBBB&V*<?? LL3v;s;<  #T #U #C CS!GB s7NO: .^ 9 6:'  V 3%&&9$L'N!N!% %B&(DsP n4, n::n: n??oA(o 7Bo%o60o; ooo32o3)rrrr)rlist[dict[Expr, Expr]]returnr$)__doc__ __future__r sympy.corerrrrrr sympy.core.assumptionsr sympy.core.exprtoolsr sympy.core.functionr r rrrrrrrrrsympy.core.logicrrsympy.core.numbersrrrsympy.core.intfuncrrsympy.core.powerrsympy.core.relationalrr sympy.core.sortingr!r"sympy.core.sympifyr#r$sympy.core.traversalr%sympy.logic.boolalgr&r'sympy.functionsr(r)r*r+r,r-r.r/r0r1r2r3r4r5r6(sympy.functions.combinatorial.factorialsr7%sympy.functions.elementary.hyperbolicr8$sympy.functions.elementary.piecewiser9r:(sympy.functions.elementary.trigonometricr;sympy.integrals.integralsr<sympy.ntheory.factor_r=sympy.simplifyr>r?r@rArBrCrDrErFrGrHsympy.simplify.sqrtdenestrIsympy.simplify.furJrKrLrMsympy.strategies.rlrNsympy.matrices.exceptionsrOsympy.matricesrPrQ sympy.polysrRrSrTrUsympy.polys.solversrVrWsympy.polys.polyerrorsrXrYsympy.polys.polytoolsrZsympy.utilities.lambdifyr[sympy.utilities.miscr\r]sympy.utilities.iterablesr^r_r`rarbrcrdresympy.utilities.decoratorrfrrgsympy.solvers.polysysrhtypesri collectionsrj itertoolsrkrlrrrrrrrjrCrDrFrErrrrlr]rfrirsr}rrrrrrsympy.solvers.bivariaterrrrrrrOs #994-....2880 (8030<<<<<=DJJ.*133'>(33@D%-3HHH93#+*>ZD 0JfkJ``EF  tn %; IXRslPf7tAH$ND6*;,: , . 1 B NFFR~Brl 44r