Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
""" This module contains functions to:
- solve a single equation for a single variable, in any domain either real or complex.
- solve a system of linear equations with N variables and M equations.
- solve a system of Non Linear Equations with N variables and M equations """
expand_log) acos, asin, acsc, asec, arg, piecewise_fold, Piecewise) HyperbolicFunction) Union, ConditionSet, ImageSet, Complement, Contains) RootOf, factor) _simple_dens, recast_to_symbols, _ispow)
"""Return ``f``, with all objects given by ``atoms`` replaced with Dummy symbols, ``d``, and the list of replacements, ``(d, e)``, where ``e`` is an object of type given by ``atoms`` in which any other instances of atoms have been recursively replaced with Dummy symbols, too. The tuples are ordered so that if they are applied in sequence, the origin ``f`` will be restored.
Examples ========
>>> from sympy import cos >>> from sympy.abc import x >>> from sympy.solvers.solveset import _masked
>>> f = cos(cos(x) + 1) >>> f, reps = _masked(cos(1 + cos(x)), cos) >>> f _a1 >>> reps [(_a1, cos(_a0 + 1)), (_a0, cos(x))] >>> for d, e in reps: ... f = f.xreplace({d: e}) >>> f cos(cos(x) + 1) """
r""" Reduce the complex valued equation ``f(x) = y`` to a set of equations ``{g(x) = h_1(y), g(x) = h_2(y), ..., g(x) = h_n(y) }`` where ``g(x)`` is a simpler function than ``f(x)``. The return value is a tuple ``(g(x), set_h)``, where ``g(x)`` is a function of ``x`` and ``set_h`` is the set of function ``{h_1(y), h_2(y), ..., h_n(y)}``. Here, ``y`` is not necessarily a symbol.
The ``set_h`` contains the functions, along with the information about the domain in which they are valid, through set operations. For instance, if ``y = Abs(x) - n`` is inverted in the real domain, then ``set_h`` is not simply `{-n, n}` as the nature of `n` is unknown; rather, it is: `Intersection([0, oo) {n}) U Intersection((-oo, 0], {-n})`
By default, the complex domain is used which means that inverting even seemingly simple functions like ``exp(x)`` will give very different results from those obtained in the real domain. (In the case of ``exp(x)``, the inversion via ``log`` is multi-valued in the complex domain, having infinitely many branches.)
If you are working with real values only (or you are not sure which function to use) you should probably set the domain to ``S.Reals`` (or use `invert\_real` which does that automatically).
Examples ========
>>> from sympy.solvers.solveset import invert_complex, invert_real >>> from sympy.abc import x, y >>> from sympy import exp, log
When does exp(x) == y?
>>> invert_complex(exp(x), y, x) (x, ImageSet(Lambda(_n, I*(2*_n*pi + arg(y)) + log(Abs(y))), S.Integers)) >>> invert_real(exp(x), y, x) (x, Intersection(S.Reals, {log(y)}))
When does exp(x) == 1?
>>> invert_complex(exp(x), 1, x) (x, ImageSet(Lambda(_n, 2*_n*I*pi), S.Integers)) >>> invert_real(exp(x), 1, x) (x, {0})
See Also ======== invert_real, invert_complex """
else:
""" Inverts a real-valued function. Same as _invert, but sets the domain to ``S.Reals`` before inverting. """
"""Helper function for _invert."""
TrigonometricFunction, HyperbolicFunction, )): raise ValueError("Only functions with one argument are supported.") imageset(Lambda(n, f.inverse()(n)), g_ys), symbol)
# f = g + h
# f = g*h
), g_ys.intersect( Interval.Ropen(S.Zero, S.Infinity)))
else: else: "defined for negative x")
imageset(Lambda(n, log(n, base, evaluate=False)), g_ys), symbol) #special case: 0**x - 1
lambda a: 2*n*pi + F(a), lambda a: 2*n*pi - F(a),)
"""Helper function for _invert."""
# f = g + h
# f = g*h
not isinstance(f, TrigonometricFunction) and \ not isinstance(f, HyperbolicFunction) and \ not isinstance(f, exp): raise ValueError("Only functions with one argument are supported.") imageset(Lambda(n, f.inverse()(n)), g_ys), symbol)
log(Abs(g_y))), S.Integers) for g_y in g_ys if g_y != 0])
"""Helper function for inverting absolute value functions.
Returns the complete result of inverting an absolute value function along with the conditions which must also be satisfied.
If it is certain that all these conditions are met, a `FiniteSet` of all possible solutions is returned. If any condition cannot be satisfied, an `EmptySet` is returned. Otherwise, a `ConditionSet` of the solutions, with all the required conditions specified, is returned.
""" # this could be used for FiniteSet, but the # results are more compact if they aren't, e.g. # ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n}) vs # Union(Intersection(Interval(0, oo), {n}), Intersection(Interval(-oo, 0), {-n})) # for the solution of abs(x) - n raise NotImplementedError
# check conditions: all these must be true. If any are unknown # then return them as conditions which must be satisfied for i in unknown]) else: # this is slightly different than above: instead of solving # +/-f on positive values, here we solve for f on +/- g_ys imageset(Lambda(n, n), g_ys), imageset(Lambda(n, -n), g_ys)), symbol)
"""Returns False if point p is infinite or any subexpression of f is infinite or becomes so after replacing symbol with p. If none of these conditions is met then True will be returned.
Examples ========
>>> from sympy import Mul, oo >>> from sympy.abc import x >>> from sympy.solvers.solveset import domain_check >>> g = 1/(1 + (1/(x + 1))**2) >>> domain_check(g, x, -1) False >>> domain_check(x**2, x, 0) True >>> domain_check(1/x, x, oo) False
* The function relies on the assumption that the original form of the equation has not been changed by automatic simplification.
>>> domain_check(x/x, x, 0) # x/x is automatically simplified to 1 True
* To deal with automatic evaluations use evaluate=False:
>>> domain_check(Mul(x, 1/x, evaluate=False), x, 0) False """
# helper for domain check else: for g in f.args])
""" Return True if the given expression is finite. For symbols that don't assign a value for `complex` and/or `real`, the domain will be used to assign a value; symbols that don't assign a value for `finite` will be made finite. All other assumptions are left unmodified. """ # if this gets set it will make complex=True, too else: # don't change 'real' because being complex implies # nothing about being real
""" Tests whether the equation is an equation of the given function class.
The given equation belongs to the given function class if it is comprised of functions of the function class which are multiplied by or added to expressions independent of the symbol. In addition, the arguments of all such functions must be linear in the symbol as well.
Examples ========
>>> from sympy.solvers.solveset import _is_function_class_equation >>> from sympy import tan, sin, tanh, sinh, exp >>> from sympy.abc import x >>> from sympy.functions.elementary.trigonometric import (TrigonometricFunction, ... HyperbolicFunction) >>> _is_function_class_equation(TrigonometricFunction, exp(x) + tan(x), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x) True >>> _is_function_class_equation(TrigonometricFunction, tan(x**2), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x + 2), x) True >>> _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x) True """ for arg in f.args)
else:
else:
""" solve rational functions""" # The polynomial formed from g could end up having # coefficients in a ring over which finding roots # isn't implemented yet, e.g. ZZ[a] for some symbol a else:
"""Function to call other helpers to solve trigonometric equations """ except BaseException as error: sol = sol1 if sol1.count_ops() < sol.count_ops(): sol = sol1 else: raise NotImplementedError(filldedent(''' Solution to this kind of trigonometric equations is yet to be implemented'''))
"""Primary Helper to solve trigonometric equations """ return ConditionSet(symbol, Eq(f, 0), S.Reals)
raise NotImplementedError
raise NotImplementedError for s in solns]) else:
"""Secondary helper to solve trigonometric equations, called when first helper fails """
except ValueError: raise ValueError("give up, we can't solve if this is not a polynomial in x") raise ValueError("degree of variable inside polynomial should not exceed one") continue
# ilcm() and igcd() require more than one argument else:
return ConditionSet(symbol, Eq(f_original, 0), domain)
for s in solns]) result = Union(result, dsol) # would be another sol at Lim(denom-->oo) elif solns is S.EmptySet: return S.EmptySet else: return ConditionSet(symbol, Eq(f_original, 0), S.Reals)
""" Solve the equation using polynomial techniques if it already is a polynomial equation or, with a change of variables, can be made so. """ quintics=True, domain='EX') else: else: result = ConditionSet(symbol, Eq(f, 0), domain) else: result = ConditionSet(symbol, Eq(f, 0), domain)
quintics=True).keys())
else: else:
# this is to simplify solutions like -sqrt(-I) to sqrt(2)/2 # - sqrt(2)*I/2. We are not expanding for solution with symbols # or undefined functions because that makes the solution more complicated. # For example, expand_complex(a) returns re(a) + I*im(a) for s in result]): else: return ConditionSet(symbol, Eq(f, 0), domain)
""" Returns (bool, den) where bool is True if the term has a non-integer rational power and den is the denominator of the expression's exponent.
Examples ========
>>> from sympy.solvers.solveset import _has_rational_power >>> from sympy import sqrt >>> from sympy.abc import x >>> _has_rational_power(sqrt(x), x) (True, 2) >>> _has_rational_power(x**2, x) (False, 1) """ return (False, S.One) and pattern_match[p].has(symbol):
or isinstance(pattern_match[a], Mul): else:
""" Helper function to solve equations with radicals """ Union(*[solveset_solver(g, symbol) for g in denoms(f, symbol)]) else: for g_y in g_y_s])
else: else:
""" Helper function to solve equation involving absolute value function """ Absolute values cannot be inverted in the complex domain.'''))
relational=False, domain=domain, continuous=True)
symbol).intersect(q_pos_cond) symbol).intersect(q_neg_cond) else:
""" Function to solve equations via the principle of "Decomposition and Rewriting".
Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S >>> from sympy.solvers.solveset import solve_decomposition as sd >>> x = Symbol('x') >>> f1 = exp(2*x) - 3*exp(x) + 2 >>> sd(f1, x, S.Reals) {0, log(2)} >>> f2 = sin(x)**2 + 2*sin(x) + 1 >>> pprint(sd(f2, x, S.Reals), use_unicode=False) 3*pi {2*n*pi + ---- | n in S.Integers} 2 >>> f3 = sin(x + 2) >>> pprint(sd(f3, x, S.Reals), use_unicode=False) {2*n*pi - 2 | n in S.Integers} U {2*n*pi - 2 + pi | n in S.Integers}
""" # decompose the given function # `y_s` represents the set of values for which the function `g` is to be # solved. # `solutions` represent the solutions of the equations `g = y_s` or # `g = 0` depending on the type of `y_s`. # As we are interested in solving the equation: f = 0
else: iter_iset = (y_s,)
# y_s is not in the range of g in g_s, so no solution exists #in the given domain
elif isinstance(new_solutions, Intersection): if isinstance(new_solutions.args[1], FiniteSet): new_exprs = new_solutions.args[1]
return ConditionSet(symbol, Eq(f, 0), domain)
"""Helper for solveset to return a result from an expression that has already been sympify'ed and is known to contain the given symbol.""" # _check controls whether the answer is checked or not
S.NegativeInfinity]):
# assign the solvers to use
for m in f.args): # if f(x) and g(x) are both finite we can say that the solution of # f(x)*g(x) == 0 is same as Union(f(x) == 0, g(x) == 0) is not true in # general. g(x) can grow to infinitely large for the values where # f(x) == 0. To be sure that we are not silently allowing any # wrong solutions we are using this technique only if both f and g are # finite for a finite input. _is_function_class_equation(HyperbolicFunction, f, symbol): in_set = in_set.as_set()
raise NotImplementedError(filldedent(''' Inequalities in the complex domain are not supported. Try the real domain by setting domain=S.Reals''')) f, symbol, domain=domain, relational=False) else: # do some very minimal simplification since # repeated inversion may have left the result # in a state that other solvers (e.g. poly) # would have simplified; this is done here # rather than in the inverter since here it # is only done once whereas there it would # be repeated for each step of the inversion signsimp(i).as_content_primitive()) for i in rhs_s])
for g in equation.args) or _has_rational_power( equation, symbol)[0]: symbol, solver) else: # may be a transcendental type equation else: else:
# it wasn't solved or has enumerated all conditions # -- leave it alone
# whittle away all but the symbol-containing core # to use this for testing
# check the result for invalid solutions if isinstance(s, RootOf) or domain_check(fx, symbol, s)])
""" Helper function for solving exponential equations.
Exponential equations are the type of equations which includes a variable located in the exponent. For example `5**(2*x + 3) - 5**(3*x - 1)`. The function evaluates exponetial equations having two arguments, i.e, exponential equations having only two exponent terms (like the one above).
The helper takes the equation as the input, tries to reduce the equation to log form (if possible) and returns the modified equation.
* Proof of correctness of the method
The logarithm is the inverse function to exponentiation. The defining relation between exponentiation and logarithm is:
log(x, b) = y if b**y = x
Therefore if we are given an equation with exponent terms, we can convert every term to its corresponding log form. This is achieved by taking logarithms and expanding them using log identities so that the equations can be easily handled by `solveset`. For example: 3**(2*x) = 2**(x + 3). Taking log both sides will reduce the equation to `2*x*log(3) - (x + 3)*log(2)`. This is easily handled by solveset. """
except TypeError: raise ValueError("Equations with more than two arguments are not\ supported")
""" Helper to check whether an equation is exponential or not.
Returns True if it is of exponential type otherwise False. This helper is specifically designed to determine two argument type exponential equations. Two argument type exponential equations are the ones which consists of only two exponent terms. Therefore it returns False if `f` does not contains exactly two arguments.
It checks whether any of the symbol dependent term contains power. If so there is a chance that the equation is of exponential type, hence returns True otherwise False.
Examples ========
>>> from sympy import symbols >>> from sympy.solvers.solveset import _check_expo as check >>> x = symbols('x') >>> check(3**x - 2, x) True >>> check(2*x, x) False """
""" Function to solve transcendental equations. It is a helper to solveset and should be used internally as of now. `transolve` currently supports the following class of equations:
- Exponential equations
Parameters ==========
``f`` can be any (supported) transcendental equation that needs to be solved. This needs to be an expression, which is assumed to be equal to 0.
``symbol`` is variable for which the equation is solved. This needs to be of class `Symbol`.
``domain`` is a set over which the equation is solved. This needs to be of class `Set`.
How to use transolve ====================
`transolve` should be used as an internal function. There should be an internal call to `transolve`, passing all the three above arguments as parameters. These three parameters should be sympy instances.
How transolve works ===================
The main idea behind `transolve` is to make it modular, extensible, robust and easy to understand. For this to be achieved `transolve` uses two types of helper functions to solve equation of a particular class:
Identifying helpers: These helpers are used to determine whether a given equation belongs to a certain class of equation or not. Heuristics are implemented to determine this. These functions return either True or False.
Solving helpers: Once identified that the equation belongs to a particular class, another helper is invoked which will be responsible to either solve the equation fully or reduce to a better form for `solveset` to handle it. A generalized algorithm or heuristic is implemented to get the output.
* Philosophy behind the module
`transolve` comes into action when solveset is unable to solve the equation as a last resort to get the solutions. So the idea is that, first it tries to invert the equation to get the `lhs` and the `rhs`. Depending on the general form of the class of the equation the equations are sent to different cases, like for example, logarithmic and exponential equations takes the form as `a*f(x) + b*g(x)`, where f(x) and g(x) are power (or log) terms, therefore they are included in `Add` case. Similarly different classes of equation can be included in cases depending on their general form. Once figuring out, different identifying helper conditions are included to check which class the equation belongs. If the equation belongs to a particular class it is solved by a call to its respective solving helper. This helper either solves the equation completely or transforms to a better form for `solveset` to handle. If the equation is solved the result is returned otherwise a `ConditionSet` is returned.
How transolve is better than _tsolve ====================================
1) Better output
`transolve` provides a better output to some equations than `_tsolve`. Though result from both the functions are correct it's just that the one from transolve is easy to understand and appropriate. This is because transolve smartly evaluates the result minimising it wherever necessary.
Consider a simple exponential equation 3**(2*x) - 2**(x + 3) transolve gives the output as {(-3*log(2)/(-2*log(3) + log(2))}, whereas _tsolve would return [-log(2**(3/log(2/9)))].`transolve's` output seems more simple, readable and appropriate as compared to the latter one.
2) Extensible
The API of `transolve` is designed such that it is easily extensible, i.e, it is easy to add a new class of equation solver without having to mess with the API or solving code of other helpers. The idea is that the function itself contains call to different helpers that identifies and solves the equation. So to make new class of equation solve, you must add a helper that identifies that particular class of the equation and another helper that solves that type of equations. You should read the below section to get more insight on how to add new class of equations in transolve.
3) Modular
`transolve` is designed to be modular i.e, for every class of equation a separate helper for identification and solving is implemented. This makes it easy to change or modify any of the method implemented directly in the helpers without interfering with the actual structure of the API.
4) Less complex API
Since modular approach is used in transolve, the API automatically becomes less complex to read and understand unlike in `_tsolve` where the API structure is a mess and lots of recursive and function calls makes it more hard to understand.
5) Faster Computation
Equation solving via transolve is much faster as compared to `_tsolve`. The way equations are treated in solve is complicated which make it a bit time consuming. `solve` tries every possibility to solve the equation and in process it gets into each and every condition and starts solving the equation to get an answer, if the result is not achieved the equation is solved by another means. Therefore this series of solving makes it a bit slow. Whereas in `transolve` computation begins only when the equation is identified of being a particular type.
How to add new class of equations =================================
`transolve` is designed in such a way that it becomes an easy task to add a new class of equation solver.
The first task that needs to be done for adding your own solver is to decide from where its `identificaion helper` will be invoked. To do so determine the general form of the class of the equation to place the invocation of the identification helper to an appropriate place within transolve, for example the general form of the exponential equations is `a*f(x) + b*g(x)` so we need to place the invocation condition inside `Add` case. Once the place for identification helper is determined, you can add a call to solving helper. For your class of equation you need to define your own identification and solving helpers. The identification helper should be implemented for generalised cases and should return either `True` if the given equation belongs to the class otherwise `False`. Solving helpers needs to be implemented with such heuristics or algorithms that solves most of the equations belonging to that class. The value returned from this helper should be handled properly in the main (transolve) function itself. It could be either the exact solution or a reduced form of the equation which `solveset` can handle.
Apart from this, few other things needs to be taken care while adding an equation solver:
- Naming conventions Name of the identification helper should be like `_check_class`, where `class` will be the name or abbreviation of the class of equation. The solving helper will be named as `_class_solver`. For eg: for exponential equation it becomes `_check_expo` and `_expo_solver_`. - Be sure to consider consider corner cases. - Adding tests for each method (if necessary). - Adding a docstring to your helper that describes the method implemented with its proof of correctness by explaining with few examples. Since most of the methods devised to identify and solve particular class of equations are mostly heuristics therefore it becomes necessary to provide proof of correctness of these methods. Following things needs to be included while writing the documentation for the helpers: - What is the purpose of the helper. - How it solves the equation and how does it identifies the equation. - Examples should be included to prove its correctness. - What are the input parameters and what does the helper returns.
Examples ========
>>> from sympy.solvers.solveset import _transolve >>> from sympy import symbols, S
>>> x = symbols('x', real=True) >>> _transolve(5**(x-3) - 3**(2*x + 1), x, S.Reals) {-log(375)/(-log(5) + 2*log(3))} """
# invert_complex handles the call to the desired inverter based # on the domain specified.
else: # do we need a loop for rhs_s? # Can't determine a case as of now.
# trying to convert to P.O.S form
# check if it is exponential type equation
# there is chance that ConditionSet is returned from # any of the helper which will have modified equation # therefore to get the original equation in the ConditionSet # this condition is necessary.
r"""Solves a given inequality or equation with set as output
Parameters ==========
f : Expr or a relational. The target equation or inequality symbol : Symbol The variable for which the equation is solved domain : Set The domain over which the equation is solved
Returns =======
Set A set of values for `symbol` for which `f` is True or is equal to zero. An `EmptySet` is returned if `f` is False or nonzero. A `ConditionSet` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented.
`solveset` claims to be complete in the solution set that it returns.
Raises ======
NotImplementedError The algorithms to solve inequalities in complex domain are not yet implemented. ValueError The input is not valid. RuntimeError It is a bug, please report to the github issue tracker.
Notes =====
Python interprets 0 and 1 as False and True, respectively, but in this function they refer to solutions of an expression. So 0 and 1 return the Domain and EmptySet, respectively, while True and False return the opposite (as they are assumed to be solutions of relational expressions).
See Also ========
solveset_real: solver for real domain solveset_complex: solver for complex domain
Examples ========
>>> from sympy import exp, sin, Symbol, pprint, S >>> from sympy.solvers.solveset import solveset, solveset_real
* The default domain is complex. Not specifying a domain will lead to the solving of the equation in the complex domain (and this is not affected by the assumptions on the symbol):
>>> x = Symbol('x') >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in S.Integers}
>>> x = Symbol('x', real=True) >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in S.Integers}
* If you want to use `solveset` to solve the equation in the real domain, provide a real domain. (Using `solveset\_real` does this automatically.)
>>> R = S.Reals >>> x = Symbol('x') >>> solveset(exp(x) - 1, x, R) {0} >>> solveset_real(exp(x) - 1, x) {0}
The solution is mostly unaffected by assumptions on the symbol, but there may be some slight difference:
>>> pprint(solveset(sin(x)/x,x), use_unicode=False) ({2*n*pi | n in S.Integers} \ {0}) U ({2*n*pi + pi | n in S.Integers} \ {0})
>>> p = Symbol('p', positive=True) >>> pprint(solveset(sin(p)/p, p), use_unicode=False) {2*n*pi | n in S.Integers} U {2*n*pi + pi | n in S.Integers}
* Inequalities can be solved over the real domain only. Use of a complex domain leads to a NotImplementedError.
>>> solveset(exp(x) > 1, x, R) Interval.open(0, oo)
"""
else: raise NotImplementedError(filldedent(''' relationship between value and 0 is unknown: %s''' % b))
The independent variable must be specified for a multivariate equation.''')) # the xreplace will be needed if a ConditionSet is returned
).xreplace({r: symbol}) except InconsistentAssumptions: pass # Abs has its own handling method which avoids the # rewriting property that the first piece of abs(x) # is for x >= 0 and the 2nd piece for x < 0 -- solutions # can look better if the 2nd condition is x <= 0. Since # the solution is a set, duplication of results is not # an issue, e.g. {y, -y} when y is 0 will be {0} # everything *in* an Abs
"""Solves an equation using solveset and returns the solution in accordance with the `solve` output API.
Returns =======
We classify the output based on the type of solution returned by `solveset`.
Solution | Output ---------------------------------------- FiniteSet | list
ImageSet, | list (if `f` is periodic) Union |
EmptySet | empty list
Others | None
Raises ======
NotImplementedError A ConditionSet is the input.
Examples ========
>>> from sympy.solvers.solveset import solvify, solveset >>> from sympy.abc import x >>> from sympy import S, tan, sin, exp >>> solvify(x**2 - 9, x, S.Reals) [-3, 3] >>> solvify(sin(x) - 1, x, S.Reals) [pi/2] >>> solvify(tan(x), x, S.Reals) [0] >>> solvify(exp(x) - 1, x, S.Complexes)
>>> solvify(exp(x) - 1, x, S.Reals) [0]
"""
raise NotImplementedError('solveset is unable to solve this equation.')
else:
else: result += solution
############################################################################### ################################ LINSOLVE ##################################### ###############################################################################
r""" Converts a given System of Equations into Matrix form. Here `equations` must be a linear system of equations in `symbols`. The order of symbols in input `symbols` will determine the order of coefficients in the returned Matrix.
The Matrix form corresponds to the augmented matrix form. For example:
.. math:: 4x + 2y + 3z = 1 .. math:: 3x + y + z = -6 .. math:: 2x + 4y + 9z = 2
This system would return `A` & `b` as given below:
::
[ 4 2 3 ] [ 1 ] A = [ 3 1 1 ] b = [-6 ] [ 2 4 9 ] [ 2 ]
Examples ========
>>> from sympy import linear_eq_to_matrix, symbols >>> x, y, z = symbols('x, y, z') >>> eqns = [x + 2*y + 3*z - 1, 3*x + y + z + 6, 2*x + 4*y + 9*z - 2] >>> A, b = linear_eq_to_matrix(eqns, [x, y, z]) >>> A Matrix([ [1, 2, 3], [3, 1, 1], [2, 4, 9]]) >>> b Matrix([ [ 1], [-6], [ 2]]) >>> eqns = [x + z - 1, y + z, x - y] >>> A, b = linear_eq_to_matrix(eqns, [x, y, z]) >>> A Matrix([ [1, 0, 1], [0, 1, 1], [1, -1, 0]]) >>> b Matrix([ [1], [0], [0]])
* Symbolic coefficients are also supported
>>> a, b, c, d, e, f = symbols('a, b, c, d, e, f') >>> eqns = [a*x + b*y - c, d*x + e*y - f] >>> A, B = linear_eq_to_matrix(eqns, x, y) >>> A Matrix([ [a, b], [d, e]]) >>> B Matrix([ [c], [f]])
"""
are to be found.')
# initialize Matrix with symbols + 1 columns
# Extract coeff of symbols
# append constant term (term free from symbols)
# insert equations coeff's into rows
# delete the initialized (Ist) trivial row
r""" Solve system of N linear equations with M variables, which means both under - and overdetermined systems are supported. The possible number of solutions is zero, one or infinite. Zero solutions throws a ValueError, where as infinite solutions are represented parametrically in terms of given symbols. For unique solution a FiniteSet of ordered tuple is returned.
All Standard input formats are supported: For the given set of Equations, the respective input types are given below:
.. math:: 3x + 2y - z = 1 .. math:: 2x - 2y + 4z = -2 .. math:: 2x - y + 2z = 0
* Augmented Matrix Form, `system` given below:
::
[3 2 -1 1] system = [2 -2 4 -2] [2 -1 2 0]
* List Of Equations Form
`system = [3x + 2y - z - 1, 2x - 2y + 4z + 2, 2x - y + 2z]`
* Input A & b Matrix Form (from Ax = b) are given as below:
::
[3 2 -1 ] [ 1 ] A = [2 -2 4 ] b = [ -2 ] [2 -1 2 ] [ 0 ]
`system = (A, b)`
Symbols can always be passed but are actually only needed when 1) a system of equations is being passed and 2) the system is passed as an underdetermined matrix and one wants to control the name of the free variables in the result. An error is raised if no symbols are used for case 1, but if no symbols are provided for case 2, internally generated symbols will be provided. When providing symbols for case 2, there should be at least as many symbols are there are columns in matrix A.
The algorithm used here is Gauss-Jordan elimination, which results, after elimination, in a row echelon form matrix.
Returns =======
A FiniteSet containing an ordered tuple of values for the unknowns for which the `system` has a solution. (Wrapping the tuple in FiniteSet is used to maintain a consistent output format throughout solveset.)
Returns EmptySet(), if the linear system is inconsistent.
Raises ======
ValueError The input is not valid. The symbols are not given.
Examples ========
>>> from sympy import Matrix, S, linsolve, symbols >>> x, y, z = symbols("x, y, z") >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b = Matrix([3, 6, 9]) >>> A Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b Matrix([ [3], [6], [9]]) >>> linsolve((A, b), [x, y, z]) {(-1, 2, 0)}
* Parametric Solution: In case the system is underdetermined, the function will return a parametric solution in terms of the given symbols. Those that are free will be returned unchanged. e.g. in the system below, `z` is returned as the solution for variable z; it can take on any value.
>>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> b = Matrix([3, 6, 9]) >>> linsolve((A, b), x, y, z) {(z - 1, -2*z + 2, z)}
If no symbols are given, internally generated symbols will be used. The `tau0` in the 3rd position indicates (as before) that the 3rd variable -- whatever it's named -- can take on any value:
>>> linsolve((A, b)) {(tau0 - 1, -2*tau0 + 2, tau0)}
* List of Equations as input
>>> Eqns = [3*x + 2*y - z - 1, 2*x - 2*y + 4*z + 2, - x + y/2 - z] >>> linsolve(Eqns, x, y, z) {(1, -2, -2)}
* Augmented Matrix as input
>>> aug = Matrix([[2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> aug Matrix([ [2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> linsolve(aug, x, y, z) {(3/10, 2/5, 0)}
* Solve for symbolic coefficients
>>> a, b, c, d, e, f = symbols('a, b, c, d, e, f') >>> eqns = [a*x + b*y - c, d*x + e*y - f] >>> linsolve(eqns, x, y) {((-b*f + c*e)/(a*e - b*d), (a*f - c*d)/(a*e - b*d))}
* A degenerate system returns solution as set of given symbols.
>>> system = Matrix(([0, 0, 0], [0, 0, 0], [0, 0, 0])) >>> linsolve(system, x, y) {(x, y)}
* For an empty system linsolve returns empty set
>>> linsolve([], x) EmptySet()
"""
# If second argument is an iterable
# unpack system
# 1). (A, b)
# 2). (eq1, eq2, ...) When passing a system of equations, the explicit symbols for which a solution is being sought must be given as a sequence, too. ''')) # since we are checking it, we might as well take the # expanded expr that it will give %s contains non-linear terms in the variables to be evaluated ''') % eq)
symbols and not isinstance(symbols, GeneratorType) and isinstance(symbols[0], Matrix)): # 3). A augmented with b
raise ValueError(filldedent(''' At least one of the symbols provided already appears in the system to be solved. One way to avoid this is to use Dummy symbols in the generator, e.g. numbered_symbols('%s', cls=Dummy) ''' % symbols[0].name.rstrip('1234567890')))
# No solution
# Replace free parameters with free symbols # re-use the parameters but put them in order # params [x, y, z] # free_symbols [2, 0, 4] # idx [1, 0, 2] # simultaneous replacements {y: x, x: y, z: z} else: the number of symbols passed should have a length equal to the number of %s. ''' % syms_needed_msg))
############################################################################## # ------------------------------nonlinsolve ---------------------------------# ##############################################################################
# return conditionset Tuple(*symbols), FiniteSet(*eqs), S.Complexes)
exclude=[], all_symbols=None): r""" Solves the `system` using substitution method. It is used in `nonlinsolve`. This will be called from `nonlinsolve` when any equation(s) is non polynomial equation.
Parameters ==========
system : list of equations The target system of equations symbols : list of symbols to be solved. The variable(s) for which the system is solved known_symbols : list of solved symbols Values are known for these variable(s) result : An empty list or list of dict If No symbol values is known then empty list otherwise symbol as keys and corresponding value in dict. exclude : Set of expression. Mostly denominator expression(s) of the equations of the system. Final solution should not satisfy these expressions. all_symbols : known_symbols + symbols(unsolved).
Returns =======
A FiniteSet of ordered tuple of values of `all_symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `all_symbols`. If parameter `all_symbols` is None then same as symbols present in the parameter `symbols`.
Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered.
Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset.
Raises ======
ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type.
Examples ========
>>> from sympy.core.symbol import symbols >>> x, y = symbols('x, y', real=True) >>> from sympy.solvers.solveset import substitution >>> substitution([x + y], [x], [{y: 1}], [y], set([]), [x, y]) {(-1, 1)}
* when you want soln should not satisfy eq `x + 1 = 0`
>>> substitution([x + y], [x], [{y: 1}], [y], set([x + 1]), [y, x]) EmptySet() >>> substitution([x + y], [x], [{y: 1}], [y], set([x - 1]), [y, x]) {(1, -1)} >>> substitution([x + y - 1, y - x**2 + 5], [x, y]) {(-3, 4), (2, -1)}
* Returns both real and complex solution
>>> x, y, z = symbols('x, y, z') >>> from sympy import exp, sin >>> substitution([exp(x) - sin(y), y**2 - 4], [x, y]) {(log(sin(2)), 2), (ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), S.Integers), -2), (ImageSet(Lambda(_n, 2*_n*I*pi + Mod(log(sin(2)), 2*I*pi)), S.Integers), 2)}
>>> eqs = [z**2 + exp(2*x) - sin(y), -3 + exp(-y)] >>> substitution(eqs, [y, z]) {(-log(3), -sqrt(-exp(2*x) - sin(log(3)))), (-log(3), sqrt(-exp(2*x) - sin(log(3)))), (ImageSet(Lambda(_n, 2*_n*I*pi + Mod(-log(3), 2*I*pi)), S.Integers), ImageSet(Lambda(_n, -sqrt(-exp(2*x) + sin(2*_n*I*pi + Mod(-log(3), 2*I*pi)))), S.Integers)), (ImageSet(Lambda(_n, 2*_n*I*pi + Mod(-log(3), 2*I*pi)), S.Integers), ImageSet(Lambda(_n, sqrt(-exp(2*x) + sin(2*_n*I*pi + Mod(-log(3), 2*I*pi)))), S.Integers))}
"""
'system is to be found.')
'Not type %s: %s')
except AttributeError: sym = False
'second argument, not type %s: %s')
# By default `all_symbols` will be same as `symbols`
# storing complements and intersection for particular symbol
# when total_solveset_call is equals to total_conditionset # means solvest fail to solve all the eq.
"""Returns the unsolved symbol present in the equation `eq`. """ # end of _unsolved_syms()
# sort such that equation with the fewest potential symbols is first. # means eq with less number of variable first in the list. ordered(system, lambda _: len(_unsolved_syms(_))))
# If solveset have returned some intersection/complement # for any symbol. It will be added in final solution. # Intersection/complement is in Interval or Set. # testcase is not added for this line(intersection) Intersection(FiniteSet(value_res), value_sym) Complement(FiniteSet(value_res), value_sym) # end of def add_intersection_complement()
"""separate the Complements, Intersections, ImageSet lambda expr and it's base_set. """ # if there is union, then need to check # Complement, Intersection, Imageset. # Order should not be changed. # extract solution and complement # complement will be added at the end # using `add_intersection_complement` method # Interval/Set will be at 0th index always if sol.args[0] != Interval(-oo, oo): # sometimes solveset returns soln # with intersection `S.Reals`, to confirm that # soln is in `domain=S.Reals` or not. We don't consider # that intersection. intersections[sym] = sol.args[0] sol = sol.args[1] # after intersection and complement Imageset should # be checked.
# if there is union of Imageset or other in soln. # no testcase is written for this if block # We need in sequence so append finteset elements # and then imageset or other. else: # ImageSet, Intersection, complement then # append them directly
# end of def _extract_main_soln()
# helper function for _append_new_soln # replace all dummy variables (Imageset lambda variables) # with zero before `checksol`. Considering fundamental soln # for `checksol`. # satisfy_exclude == true if it satisfies the expr of `exclude` list. # something like : `Mod(-log(3), 2*I*pi)` can't be # simplified right now, so `checksol` returns `TypeError`. # when this issue is fixed this try block should be # removed. Mod(-log(3), 2*I*pi) == -log(3) checksol(d, rnew_) for d in exclude) # end of def _check_exclude()
# helper function for _append_new_soln set(original_imageset.keys()) # end of def _restore_imgset()
else:
original_imageset, newresult, eq=None): """If `rnew` (A dict <symbol: soln>) contains valid soln append it to `newresult` list. `imgset_yes` is (base, dummy_var) if there was imageset in previously calculated result(otherwise empty tuple). `original_imageset` is dict of imageset expr and imageset from this result. `soln_imageset` dict of imageset expr and imageset of new soln. """ # soln should not satisfy expr present in `exclude` list. # if it is imageset # when `sym` and `sol` is `None` means no new # soln. In that case we will append rnew directly after # substituting original imagesets in rnew values if present # (second last line of this function using _restore_imgset) # use one dummy `n` which is in # previous imageset local_n for i in range( 0, len(dummy_list))]
eq, newresult, rnew, delete_soln, local_n) eq, newresult, rnew, delete_soln) # restore original imageset else: # end of def _append_new_soln()
# separate first, second priority. `res` that makes `eq` value equals # to zero, should be used first then other result(second priority). # If it is not done then we may miss some soln. else:
"""Solves the system using already known solution (result contains the dict <symbol: value>). solver is `solveset_complex` or `solveset_real`. """ # stores imageset <expr: imageset(Lambda(n, expr), base)>.
# sort such that equation with the fewest potential symbols is first. # means eq with less variable first # if imageset expr is used to solve other symbol # find the imageset and use its expr. # update eq with everything that is known so far res, None, None, imgset_yes, soln_imageset, original_imageset, newresult, eq2) # `delete_res` is true, means substituting `res` in # eq2 doesn't return `zero` or deleting the `res` # (a soln) since it staisfies expr of `exclude` # list. # Absolute values cannot be inverted in the # complex domain # separate solution and complement # complement will be added at the end # Interval will be at 0th index always # sometimes solveset returns soln # with intersection S.Reals, to confirm that # soln is in domain=S.Reals intersections[sym] = soln.args[0] # one symbol's real soln , another symbol may have # corresponding complex soln. except NotImplementedError: # If sovleset is not able to solve equation `eq2`. Next # time we may get soln using next equation `eq2` continue # don't do `continue` we may get soln # in terms of other symbol(s)
soln, soln_imageset)
# sol is not a `Union` since we checked it # before this loop sol, soln_imageset) ss in free for ss in got_symbol ]): # sol depends on previously solved symbols # then continue # put each solution in res and append the new result # in the new result list (solution for symbol `s`) # along with old results. # if any unsolved symbol is present # Then subs known value # and add this new solution # replace all lambda variables with 0. *[0 for i in range(0, len( imgst.lamda.variables))]) else: rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult) # deleting the `res` (a soln) since it staisfies # eq of `exclude` list # solution got for sym # next time use this new soln # end def _solve_using_know_values()
old_result, solveset_real) old_result, solveset_complex)
# when `total_solveset_call` is equals to `total_conditionset` # means solvest fails to solve all the eq. # return conditionset in this case
# overall result
# means {None : None} # If length < len(all_symbols) means infinite soln. # Some or all the soln is dependent on 1 symbol. # eg. {x: y+2} then final soln {x: y+2, y: y} lambda x: x not in solved_symbols, all_symbols))
# we have general soln # eg : [{x: -1, y : 1}, {x : -y , y: y}] then # return [{x : -y, y : y}] # no testcase is added for this block result_all_variables = add_intersection_complement( result_all_variables, intersections, Intersection=True, Complement=True) result_all_variables = add_intersection_complement( result_all_variables, intersections, Intersection=True) result_all_variables, complements, Complement=True)
# convert to ordered tuple # end of def substitution()
else:
# substitution method where new system is groebner basis of the system new_system, symbols, result, [], denominators) # end of def _handle_positive_dimensional()
# solve 0 dimensional poly system using `solve_poly_system` # May be some extra soln is added because # we used `unrad` in `_separate_poly_nonpoly`, so # need to check and remove if it is not a soln. # end of def _handle_zero_dimensional()
# Store denom expression if it contains symbol # try to remove sqrt and rational power else: # end of def _separate_poly_nonpoly()
r""" Solve system of N non linear equations with M variables, which means both under and overdetermined systems are supported. Positive dimensional system is also supported (A system with infinitely many solutions is said to be positive-dimensional). In Positive dimensional system solution will be dependent on at least one symbol. Returns both real solution and complex solution(If system have). The possible number of solutions is zero, one or infinite.
Parameters ==========
system : list of equations The target system of equations symbols : list of Symbols symbols should be given as a sequence eg. list
Returns =======
A FiniteSet of ordered tuple of values of `symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `symbols`.
Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered.
Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset.
For the given set of Equations, the respective input types are given below:
.. math:: x*y - 1 = 0 .. math:: 4*x**2 + y**2 - 5 = 0
`system = [x*y - 1, 4*x**2 + y**2 - 5]` `symbols = [x, y]`
Raises ======
ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type.
Examples ========
>>> from sympy.core.symbol import symbols >>> from sympy.solvers.solveset import nonlinsolve >>> x, y, z = symbols('x, y, z', real=True) >>> nonlinsolve([x*y - 1, 4*x**2 + y**2 - 5], [x, y]) {(-1, -1), (-1/2, -2), (1/2, 2), (1, 1)}
1. Positive dimensional system and complements:
>>> from sympy import pprint >>> from sympy.polys.polytools import is_zero_dimensional >>> a, b, c, d = symbols('a, b, c, d', real=True) >>> eq1 = a + b + c + d >>> eq2 = a*b + b*c + c*d + d*a >>> eq3 = a*b*c + b*c*d + c*d*a + d*a*b >>> eq4 = a*b*c*d - 1 >>> system = [eq1, eq2, eq3, eq4] >>> is_zero_dimensional(system) False >>> pprint(nonlinsolve(system, [a, b, c, d]), use_unicode=False) -1 1 1 -1 {(---, -d, -, {d} \ {0}), (-, -d, ---, {d} \ {0})} d d d d >>> nonlinsolve([(x+y)**2 - 4, x + y - 2], [x, y]) {(-y + 2, y)}
2. If some of the equations are non polynomial equation then `nonlinsolve` will call `substitution` function and returns real and complex solutions, if present.
>>> from sympy import exp, sin >>> nonlinsolve([exp(x) - sin(y), y**2 - 4], [x, y]) {(log(sin(2)), 2), (ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), S.Integers), -2), (ImageSet(Lambda(_n, 2*_n*I*pi + Mod(log(sin(2)), 2*I*pi)), S.Integers), 2)}
3. If system is Non linear polynomial zero dimensional then it returns both solution (real and complex solutions, if present using `solve_poly_system`):
>>> from sympy import sqrt >>> nonlinsolve([x**2 - 2*y**2 -2, x*y - 2], [x, y]) {(-2, -1), (2, 1), (-sqrt(2)*I, sqrt(2)*I), (sqrt(2)*I, -sqrt(2)*I)}
4. `nonlinsolve` can solve some linear(zero or positive dimensional) system (because it is using `groebner` function to get the groebner basis and then `substitution` function basis as the new `system`). But it is not recommended to solve linear system using `nonlinsolve`, because `linsolve` is better for all kind of linear system.
>>> nonlinsolve([x + 2*y -z - 3, x - y - 4*z + 9 , y + z - 4], [x, y, z]) {(3*z - 5, -z + 4, z)}
5. System having polynomial equations and only real solution is present (will be solved using `solve_poly_system`):
>>> e1 = sqrt(x**2 + y**2) - 10 >>> e2 = sqrt(y**2 + (-x + 10)**2) - 3 >>> nonlinsolve((e1, e2), (x, y)) {(191/20, -3*sqrt(391)/20), (191/20, 3*sqrt(391)/20)} >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [x, y]) {(1, 2), (1 + sqrt(5), -sqrt(5) + 2), (-sqrt(5) + 1, 2 + sqrt(5))} >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [y, x]) {(2, 1), (2 + sqrt(5), -sqrt(5) + 1), (-sqrt(5) + 2, 1 + sqrt(5))}
6. It is better to use symbols instead of Trigonometric Function or Function (e.g. replace `sin(x)` with symbol, replace `f(x)` with symbol and so on. Get soln from `nonlinsolve` and then using `solveset` get the value of `x`)
How nonlinsolve is better than old solver `_solve_system` : ===========================================================
1. A positive dimensional system solver : nonlinsolve can return solution for positive dimensional system. It finds the Groebner Basis of the positive dimensional system(calling it as basis) then we can start solving equation(having least number of variable first in the basis) using solveset and substituting that solved solutions into other equation(of basis) to get solution in terms of minimum variables. Here the important thing is how we are substituting the known values and in which equations.
2. Real and Complex both solutions : nonlinsolve returns both real and complex solution. If all the equations in the system are polynomial then using `solve_poly_system` both real and complex solution is returned. If all the equations in the system are not polynomial equation then goes to `substitution` method with this polynomial and non polynomial equation(s), to solve for unsolved variables. Here to solve for particular variable solveset_real and solveset_complex is used. For both real and complex solution function `_solve_using_know_values` is used inside `substitution` function.(`substitution` function will be called when there is any non polynomial equation(s) is present). When solution is valid then add its general solution in the final result.
3. Complement and Intersection will be added if any : nonlinsolve maintains dict for complements and Intersections. If solveset find complements or/and Intersection with any Interval or set during the execution of `substitution` function ,then complement or/and Intersection for that variable is added before returning final solution.
"""
'system is to be found.')
'system is to be found.')
# main code of def nonlinsolve() starts from here system, symbols)
# If all the equations in the system are poly # finite number of soln (Zero dimensional system) except NotImplementedError: # Right now it doesn't fail for any polynomial system of # equation. If `solve_poly_system` fails then `substitution` # method will handle it. result = substitution( polys_expr, symbols, exclude=denominators) return result
# positive dimensional system
else: # If all the equations are not polynomial. # Use `substitution` method for the system polys_expr + nonpolys, symbols, exclude=denominators) |