Elementary #
This module implements elementary functions such as trigonometric, hyperbolic, and sqrt, as well as functions like Abs , Max , Min etc.

Complex Functions #
Returns real part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use Basic.as_real_imag() or perform complex expansion on instance of this function.
Real or complex expression.
expr : Expr
Real part of expression.
Returns the real number with a zero imaginary part.
Returns imaginary part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use Basic.as_real_imag() or perform complex expansion on instance of this function.
Imaginary part of expression.
Return the imaginary part with a zero real part.
Returns the complex sign of an expression:
Real or imaginary expression.
Complex sign of expression.
Explanation
If the expression is real the sign will be:
\(1\) if expression is positive \(0\) if expression is equal to zero \(-1\) if expression is negative
If the expression is imaginary the sign will be:
\(I\) if im(expression) is positive \(-I\) if im(expression) is negative
Otherwise an unevaluated expression will be returned. When evaluated, the result (in general) will be cos(arg(expr)) + I*sin(arg(expr)) .
Abs , conjugate
Return the absolute value of the argument.
Absolute value returned can be an expression or integer depending on input arg.
This is an extension of the built-in function abs() to accept symbolic values. If you pass a SymPy expression to the built-in abs() , it will pass it automatically to Abs() .
Note that the Python built-in will return either an Expr or int depending on the argument:
Abs will always return a SymPy object.
sign , conjugate
Get the first derivative of the argument to Abs().
Returns the argument (in radians) of a complex number. The argument is evaluated in consistent convention with atan2 where the branch-cut is taken along the negative real axis and arg(z) is in the interval \((-\pi,\pi]\) . For a positive number, the argument is always 0; the argument of a negative number is \(\pi\) ; and the argument of 0 is undefined and returns nan . So the arg function will never nest greater than 3 levels since at the 4th application, the result must be nan; for a real number, nan is returned on the 3rd application.
value : Expr
Returns arc tangent of arg measured in radians.
Returns the complex conjugate [R248] of an argument. In mathematics, the complex conjugate of a complex number is given by changing the sign of the imaginary part.
Thus, the conjugate of the complex number \(a + ib\) (where \(a\) and \(b\) are real numbers) is \(a - ib\)
Complex conjugate of arg as real, imaginary or mixed expression.
https://en.wikipedia.org/wiki/Complex_conjugation
Lift argument to the Riemann surface of the logarithm, using the standard branch.
sympy.functions.elementary.exponential.exp_polar , periodic_argument
Represent the argument on a quotient of the Riemann surface of the logarithm. That is, given a period \(P\) , always return a value in \((-P/2, P/2]\) , by using \(\exp(PI) = 1\) .
A polar number.
period : Expr
The period \(P\) .
sympy.functions.elementary.exponential.exp_polar
Lift argument to the Riemann surface of the logarithm
principal_branch
Represent a polar number reduced to its principal branch on a quotient of the Riemann surface of the logarithm.
Positive real number or infinity.
This is a function of two arguments. The first argument is a polar number \(z\) , and the second one a positive real number or infinity, \(p\) . The result is z mod exp_polar(I*p) .
periodic_argument
Trigonometric #
Trigonometric functions #.
The sine function.
Returns the sine of x (measured in radians).
This function will evaluate automatically in the case \(x/\pi\) is some rational number [R252] . For example, if \(x\) is a multiple of \(\pi\) , \(\pi/2\) , \(\pi/3\) , \(\pi/4\) , and \(\pi/6\) .
csc , cos , sec , tan , cot , asin , acsc , acos , asec , atan , acot , atan2
https://en.wikipedia.org/wiki/Trigonometric_functions
https://dlmf.nist.gov/4.14
https://functions.wolfram.com/ElementaryFunctions/Sin
https://mathworld.wolfram.com/TrigonometryAngles.html
The cosine function.
Returns the cosine of x (measured in radians).
See sin() for notes about automatic evaluation.
sin , csc , sec , tan , cot , asin , acsc , acos , asec , atan , acot , atan2
https://functions.wolfram.com/ElementaryFunctions/Cos
The tangent function.
Returns the tangent of x (measured in radians).
See sin for notes about automatic evaluation.
sin , csc , cos , sec , cot , asin , acsc , acos , asec , atan , acot , atan2
https://functions.wolfram.com/ElementaryFunctions/Tan
Returns the inverse of this function.
The cotangent function.
Returns the cotangent of x (measured in radians).
sin , csc , cos , sec , tan , asin , acsc , acos , asec , atan , acot , atan2
https://functions.wolfram.com/ElementaryFunctions/Cot
The secant function.
Returns the secant of x (measured in radians).
sin , csc , cos , tan , cot , asin , acsc , acos , asec , atan , acot , atan2
https://functions.wolfram.com/ElementaryFunctions/Sec
The cosecant function.
Returns the cosecant of x (measured in radians).
sin , cos , sec , tan , cot , asin , acsc , acos , asec , atan , acot , atan2
https://functions.wolfram.com/ElementaryFunctions/Csc
Represents an unnormalized sinc function:
Automated Evaluation
Differentiation
Series Expansion
As zero’th order spherical Bessel Function
https://en.wikipedia.org/wiki/Sinc_function
Trigonometric Inverses #
The inverse sine function.
Returns the arcsine of x in radians.
asin(x) will evaluate automatically in the cases \(x \in \{\infty, -\infty, 0, 1, -1\}\) and for some instances when the result is a rational multiple of \(\pi\) (see the eval class method).
A purely imaginary argument will lead to an asinh expression.
sin , csc , cos , sec , tan , cot , acsc , acos , asec , atan , acot , atan2
https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
https://dlmf.nist.gov/4.23
https://functions.wolfram.com/ElementaryFunctions/ArcSin
The inverse cosine function.
Returns the arc cosine of x (measured in radians).
acos(x) will evaluate automatically in the cases \(x \in \{\infty, -\infty, 0, 1, -1\}\) and for some instances when the result is a rational multiple of \(\pi\) (see the eval class method).
acos(zoo) evaluates to zoo (see note in sympy.functions.elementary.trigonometric.asec )
A purely imaginary argument will be rewritten to asinh.
sin , csc , cos , sec , tan , cot , asin , acsc , asec , atan , acot , atan2
https://functions.wolfram.com/ElementaryFunctions/ArcCos
The inverse tangent function.
Returns the arc tangent of x (measured in radians).
atan(x) will evaluate automatically in the cases \(x \in \{\infty, -\infty, 0, 1, -1\}\) and for some instances when the result is a rational multiple of \(\pi\) (see the eval class method).
sin , csc , cos , sec , tan , cot , asin , acsc , acos , asec , acot , atan2
https://functions.wolfram.com/ElementaryFunctions/ArcTan
The inverse cotangent function.
Returns the arc cotangent of x (measured in radians).
acot(x) will evaluate automatically in the cases \(x \in \{\infty, -\infty, \tilde{\infty}, 0, 1, -1\}\) and for some instances when the result is a rational multiple of \(\pi\) (see the eval class method).
A purely imaginary argument will lead to an acoth expression.
acot(x) has a branch cut along \((-i, i)\) , hence it is discontinuous at 0. Its range for real \(x\) is \((-\frac{\pi}{2}, \frac{\pi}{2}]\) .
sin , csc , cos , sec , tan , cot , asin , acsc , acos , asec , atan , atan2
https://functions.wolfram.com/ElementaryFunctions/ArcCot
The inverse secant function.
Returns the arc secant of x (measured in radians).
asec(x) will evaluate automatically in the cases \(x \in \{\infty, -\infty, 0, 1, -1\}\) and for some instances when the result is a rational multiple of \(\pi\) (see the eval class method).
asec(x) has branch cut in the interval \([-1, 1]\) . For complex arguments, it can be defined [R283] as
At x = 0 , for positive branch cut, the limit evaluates to zoo . For negative branch cut, the limit
simplifies to \(-i\log\left(z/2 + O\left(z^3\right)\right)\) which ultimately evaluates to zoo .
As acos(x) = asec(1/x) , a similar argument can be given for acos(x) .
sin , csc , cos , sec , tan , cot , asin , acsc , acos , atan , acot , atan2
https://functions.wolfram.com/ElementaryFunctions/ArcSec
https://reference.wolfram.com/language/ref/ArcSec.html
The inverse cosecant function.
Returns the arc cosecant of x (measured in radians).
acsc(x) will evaluate automatically in the cases \(x \in \{\infty, -\infty, 0, 1, -1\}\) ` and for some instances when the result is a rational multiple of \(\pi\) (see the eval class method).
sin , csc , cos , sec , tan , cot , asin , acos , asec , atan , acot , atan2
https://functions.wolfram.com/ElementaryFunctions/ArcCsc
The function atan2(y, x) computes \(\operatorname{atan}(y/x)\) taking two arguments \(y\) and \(x\) . Signs of both \(y\) and \(x\) are considered to determine the appropriate quadrant of \(\operatorname{atan}(y/x)\) . The range is \((-\pi, \pi]\) . The complete definition reads as follows:
Attention: Note the role reversal of both arguments. The \(y\) -coordinate is the first argument and the \(x\) -coordinate the second.
If either \(x\) or \(y\) is complex:
Going counter-clock wise around the origin we find the following angles:
which are all correct. Compare this to the results of the ordinary \(\operatorname{atan}\) function for the point \((x, y) = (-1, 1)\)
where only the \(\operatorname{atan2}\) function reurns what we expect. We can differentiate the function with respect to both arguments:
We can express the \(\operatorname{atan2}\) function in terms of complex logarithms:
and in terms of \(\operatorname(atan)\) :
but note that this form is undefined on the negative real axis.
sin , csc , cos , sec , tan , cot , asin , acsc , acos , asec , atan , acot
https://en.wikipedia.org/wiki/Atan2
https://functions.wolfram.com/ElementaryFunctions/ArcTan2
Hyperbolic #
Hyperbolic functions #.
Base class for hyperbolic functions.
sinh , cosh , tanh , coth
sinh(x) is the hyperbolic sine of x .
The hyperbolic sine function is \(\frac{e^x - e^{-x}}{2}\) .
cosh , tanh , asinh
Returns this function as a complex coordinate.
Returns the first derivative of this function.
Returns the next term in the Taylor series expansion.
cosh(x) is the hyperbolic cosine of x .
The hyperbolic cosine function is \(\frac{e^x + e^{-x}}{2}\) .
sinh , tanh , acosh
tanh(x) is the hyperbolic tangent of x .
The hyperbolic tangent function is \(\frac{\sinh(x)}{\cosh(x)}\) .
sinh , cosh , atanh
coth(x) is the hyperbolic cotangent of x .
The hyperbolic cotangent function is \(\frac{\cosh(x)}{\sinh(x)}\) .
sinh , cosh , acoth
sech(x) is the hyperbolic secant of x .
The hyperbolic secant function is \(\frac{2}{e^x + e^{-x}}\)
sinh , cosh , tanh , coth , csch , asinh , acosh
csch(x) is the hyperbolic cosecant of x .
The hyperbolic cosecant function is \(\frac{2}{e^x - e^{-x}}\)
sinh , cosh , tanh , sech , asinh , acosh
Returns the first derivative of this function
Returns the next term in the Taylor series expansion
Hyperbolic Inverses #
asinh(x) is the inverse hyperbolic sine of x .
The inverse hyperbolic sine function.
acosh , atanh , sinh
acosh(x) is the inverse hyperbolic cosine of x .
The inverse hyperbolic cosine function.
asinh , atanh , cosh
atanh(x) is the inverse hyperbolic tangent of x .
The inverse hyperbolic tangent function.
asinh , acosh , tanh
acoth(x) is the inverse hyperbolic cotangent of x .
The inverse hyperbolic cotangent function.
asinh , acosh , coth
asech(x) is the inverse hyperbolic secant of x .
The inverse hyperbolic secant function.
asinh , atanh , cosh , acoth
https://en.wikipedia.org/wiki/Hyperbolic_function
https://dlmf.nist.gov/4.37
https://functions.wolfram.com/ElementaryFunctions/ArcSech/
acsch(x) is the inverse hyperbolic cosecant of x .
The inverse hyperbolic cosecant function.
https://functions.wolfram.com/ElementaryFunctions/ArcCsch/
Integer Functions #
Ceiling is a univariate function which returns the smallest integer value not less than its argument. This implementation generalizes ceiling to complex numbers by taking the ceiling of the real and imaginary parts separately.
sympy.functions.elementary.integers.floor
“Concrete mathematics” by Graham, pp. 87
https://mathworld.wolfram.com/CeilingFunction.html
Floor is a univariate function which returns the largest integer value not greater than its argument. This implementation generalizes floor to complex numbers by taking the floor of the real and imaginary parts separately.
sympy.functions.elementary.integers.ceiling
https://mathworld.wolfram.com/FloorFunction.html
Abstract base class for rounding functions.
Represents the fractional part of x
For real numbers it is defined [R300] as
returns zero for integer arguments
rewrite as floor
for complex arguments
sympy.functions.elementary.integers.floor , sympy.functions.elementary.integers.ceiling
https://en.wikipedia.org/wiki/Fractional_part
https://mathworld.wolfram.com/FractionalPart.html
Exponential #
The exponential function, \(e^x\) .
Returns this function as a 2-tuple representing a complex number.
sympy.functions.elementary.complexes.re , sympy.functions.elementary.complexes.im
Returns the base of the exponential function.
Calculates the next term in the Taylor series expansion.
The Lambert W function \(W(z)\) is defined as the inverse function of \(w \exp(w)\) [R302] .
In other words, the value of \(W(z)\) is such that \(z = W(z) \exp(W(z))\) for any complex number \(z\) . The Lambert W function is a multivalued function with infinitely many branches \(W_k(z)\) , indexed by \(k \in \mathbb{Z}\) . Each branch gives a different solution \(w\) of the equation \(z = w \exp(w)\) .
The Lambert W function has two partially real branches: the principal branch ( \(k = 0\) ) is real for real \(z > -1/e\) , and the \(k = -1\) branch is real for \(-1/e < z < 0\) . All branches except \(k = 0\) have a logarithmic singularity at \(z = 0\) .
https://en.wikipedia.org/wiki/Lambert_W_function
Return the first derivative of this function.
The natural logarithm function \(\ln(x)\) or \(\log(x)\) .
Logarithms are taken with the natural base, \(e\) . To get a logarithm of a different base b , use log(x, b) , which is essentially short-hand for log(x)/log(b) .
log represents the principal branch of the natural logarithm. As such it has a branch cut along the negative real axis and returns values having a complex argument in \((-\pi, \pi]\) .
Returns this function in the form (base, exponent).
Returns the first derivative of the function.
Returns \(e^x\) , the inverse function of \(\log(x)\) .
Returns the next term in the Taylor series expansion of \(\log(1+x)\) .
Represent a polar number (see g-function Sphinx documentation).
exp_polar represents the function \(Exp: \mathbb{C} \rightarrow \mathcal{S}\) , sending the complex number \(z = a + bi\) to the polar number \(r = exp(a), \theta = b\) . It is one of the main functions to construct polar numbers.
The main difference is that polar numbers do not “wrap around” at \(2 \pi\) :
apart from that they behave mostly like classical complex numbers:
sympy.simplify.powsimp.powsimp , polar_lift , periodic_argument , principal_branch
Piecewise #
Represents an expression, condition pair.
Returns the condition of this pair.
Returns the expression of this pair.
Represents a piecewise function.
Piecewise( (expr,cond), (expr,cond), … ) Each argument is a 2-tuple defining an expression and condition The conds are evaluated in turn returning the first that is True. If any of the evaluated conds are not explicitly False, e.g. x < 1 , the function is returned in symbolic form. If the function is evaluated at a place where all conditions are False, nan will be returned. Pairs where the cond is explicitly False, will be removed and no pair appearing after a True condition will ever be retained. If a single pair with a True condition remains, it will be returned, even when evaluation is False.
Booleans can contain Piecewise elements:
The folded version of this results in a Piecewise whose expressions are Booleans:
When a Boolean containing Piecewise (like cond) or a Piecewise with Boolean expressions (like folded_cond) is used as a condition, it is converted to an equivalent ITE object:
When a condition is an ITE , it will be converted to a simplified Boolean expression:
piecewise_fold , piecewise_exclusive , ITE
Return the indefinite integral of the Piecewise such that subsequent substitution of x with a value will give the value of the integral (not including the constant of integration) up to that point. To only integrate the individual parts of Piecewise, use the piecewise_integrate method.
Piecewise.piecewise_integrate
Return tuples for each argument of self that give the expression and the interval in which it is valid which is contained within the given domain. If a condition cannot be converted to a set, an error will be raised. The variable of the conditions is assumed to be real; sets of real values are returned.
Evaluate this piecewise function.
Either return a modified version of the args or, if no modifications were made, return None.
Modifications that are made here:
relationals are made canonical
any False conditions are dropped
any repeat of a previous condition is ignored
any args past one with a true condition are dropped
If there are no args left, nan will be returned. If there is a single arg with a True condition, its corresponding expression will be returned.
Return the Piecewise with each expression being replaced with its antiderivative. To obtain a continuous antiderivative, use the integrate() function or method.
Note that this does not give a continuous function, e.g. at x = 1 the 3rd condition applies and the antiderivative there is 2*x so the value of the antiderivative is 2:
The continuous derivative accounts for the integral up to the point of interest, however:
Piecewise._eval_integral
Rewrite Piecewise with mutually exclusive conditions.
expr: a SymPy expression.
Any Piecewise in the expression will be rewritten.
skip_nan: ``bool`` (default ``False``)
If skip_nan is set to True then a final NaN case will not be included.
deep: ``bool`` (default ``True``)
If deep is True then piecewise_exclusive() will rewrite any Piecewise subexpressions in expr rather than just rewriting expr itself.
An expression equivalent to expr but where all Piecewise have
been rewritten with mutually exclusive conditions.
SymPy represents the conditions of a Piecewise in an “if-elif”-fashion, allowing more than one condition to be simultaneously True. The interpretation is that the first condition that is True is the case that holds. While this is a useful representation computationally it is not how a piecewise formula is typically shown in a mathematical text. The piecewise_exclusive() function can be used to rewrite any Piecewise with more typical mutually exclusive conditions.
Note that further manipulation of the resulting Piecewise , e.g. simplifying it, will most likely make it non-exclusive. Hence, this is primarily a function to be used in conjunction with printing the Piecewise or if one would like to reorder the expression-condition pairs.
If it is not possible to determine that all possibilities are covered by the different cases of the Piecewise then a final NaN case will be included explicitly. This can be prevented by passing skip_nan=True .
Piecewise , piecewise_fold
Takes an expression containing a piecewise function and returns the expression in piecewise form. In addition, any ITE conditions are rewritten in negation normal form and simplified.
The final Piecewise is evaluated (default) but if the raw form is desired, send evaluate=False ; if trivial evaluation is desired, send evaluate=None and duplicate conditions and processing of True and False will be handled.
Piecewise , piecewise_exclusive
Miscellaneous #
The identity function
Return, if possible, the minimum value of the list. It is named Min and not min to avoid conflicts with the built-in function min .
find maximum values
Return, if possible, the maximum value of the list.
When number of arguments is equal one, then return this argument.
When number of arguments is equal two, then return, if possible, the value from (a, b) that is \(\ge\) the other.
In common case, when the length of list greater than 2, the task is more complicated. Return only the arguments, which are greater than others, if it is possible to determine directional relation.
If is not possible to determine such a relation, return a partially evaluated result.
Assumptions are used to make the decision too.
Also, only comparable arguments are permitted.
It is named Max and not max to avoid conflicts with the built-in function max .
The task can be considered as searching of supremums in the directed complete partial orders [R303] .
The source values are sequentially allocated by the isolated subsets in which supremums are searched and result as Max arguments.
If the resulted supremum is single, then it is returned.
The isolated subsets are the sets of values which are only the comparable with each other in the current set. E.g. natural numbers are comparable with each other, but not comparable with the \(x\) symbol. Another example: the symbol \(x\) with negative assumption is comparable with a natural number.
Also there are “least” elements, which are comparable with all others, and have a zero property (maximum or minimum for all elements). For example, in case of \(\infty\) , the allocation operation is terminated and only this value is returned.
if \(A > B > C\) then \(A > C\)
if \(A = B\) then \(B\) can be removed
find minimum values
https://en.wikipedia.org/wiki/Directed_complete_partial_order
https://en.wikipedia.org/wiki/Lattice_%28order%29
Returns the k -th n -th root of arg .
k : int, optional
Should be an integer in \(\{0, 1, ..., n-1\}\) . Defaults to the principal root if \(0\) .
evaluate : bool, optional
The parameter determines if the expression should be evaluated. If None , its value is taken from global_parameters.evaluate .
To get the k-th n-th root, specify k:
To get all n n-th roots you can use the rootof function. The following examples show the roots of unity for n equal 2, 3 and 4:
SymPy, like other symbolic algebra systems, returns the complex root of negative numbers. This is the principal root and differs from the text-book result that one might be expecting. For example, the cube root of -8 does not come back as -2:
The real_root function can be used to either make the principal result real (or simply to return the real root directly):
Alternatively, the n//2-th n-th root of a negative number can be computed with root:
sympy.polys.rootoftools.rootof , sympy.core.power.integer_nthroot , sqrt , real_root
https://en.wikipedia.org/wiki/Square_root
https://en.wikipedia.org/wiki/Real_root
https://en.wikipedia.org/wiki/Root_of_unity
https://en.wikipedia.org/wiki/Principal_value
https://mathworld.wolfram.com/CubeRoot.html
Returns the principal square root.
Note that sqrt(x**2) does not simplify to x.
This is because the two are not equal to each other in general. For example, consider x == -1:
This is because sqrt computes the principal square root, so the square may put the argument in a different branch. This identity does hold if x is positive:
You can force this simplification by using the powdenest() function with the force option set to True:
To get both branches of the square root you can use the rootof function:
Although sqrt is printed, there is no sqrt function so looking for sqrt in an expression will fail:
To find sqrt look for Pow with an exponent of 1/2 :
sympy.polys.rootoftools.rootof , root , real_root
Returns the principal cube root.
Note that cbrt(x**3) does not simplify to x.
This is because the two are not equal to each other in general. For example, consider \(x == -1\) :
This is because cbrt computes the principal cube root, this identity does hold if \(x\) is positive:
https://en.wikipedia.org/wiki/Cube_root
Return the real n ’th-root of arg if possible.
n : int or None, optional
If n is None , then all instances of \((-n)^{1/\text{odd}}\) will be changed to \(-n^{1/\text{odd}}\) . This will only create a real root of a principal root. The presence of other factors may cause the result to not be real.
If one creates a non-principal root and applies real_root, the result will not be real (so use with caution):
sympy.polys.rootoftools.rootof , sympy.core.power.integer_nthroot , root , sqrt
Search code, repositories, users, issues, pull requests...
Provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Solving an equation containing absolute value, with python 3 #17650
andalou commented Sep 24, 2019
smichr commented Sep 25, 2019
- 👍 2 reactions
Sorry, something went wrong.
smichr commented Sep 30, 2019
Solver Title

Generating PDF...
- Pre Algebra Order of Operations Factors & Primes Fractions Long Arithmetic Decimals Exponents & Radicals Ratios & Proportions Percent Modulo Mean, Median & Mode Scientific Notation Arithmetics
- Algebra Equations Inequalities System of Equations System of Inequalities Basic Operations Algebraic Properties Partial Fractions Polynomials Rational Expressions Sequences Power Sums Interval Notation Pi (Product) Notation Induction Logical Sets Word Problems
- Pre Calculus Equations Inequalities Simultaneous Equations System of Inequalities Polynomials Rationales Complex Numbers Polar/Cartesian Functions Arithmetic & Comp. Coordinate Geometry Plane Geometry Solid Geometry Conic Sections Trigonometry
- Calculus Derivatives Derivative Applications Limits Integrals Integral Applications Integral Approximation Series ODE Multivariable Calculus Laplace Transform Taylor/Maclaurin Series Fourier Series Fourier Transform
- Functions Line Equations Functions Arithmetic & Comp. Conic Sections Transformation
- Linear Algebra Matrices Vectors
- Trigonometry Identities Proving Identities Trig Equations Trig Inequalities Evaluate Functions Simplify
- Statistics Arithmetic Mean Geometric Mean Quadratic Mean Median Mode Order Minimum Maximum Probability Mid-Range Range Standard Deviation Variance Lower Quartile Upper Quartile Interquartile Range Midhinge Standard Normal Distribution
- Physics Mechanics
- Chemistry Chemical Reactions Chemical Properties
- Finance Simple Interest Compound Interest Present Value Future Value
- Economics Point of Diminishing Return
- Conversions Radical to Exponent Exponent to Radical To Fraction To Decimal To Mixed Number To Improper Fraction Radians to Degrees Degrees to Radians Hexadecimal Scientific Notation Distance Weight Time
- Pre Algebra
- One-Step Addition
- One-Step Subtraction
- One-Step Multiplication
- One-Step Division
- One-Step Decimals
- Two-Step Integers
- Two-Step Add/Subtract
- Two-Step Multiply/Divide
- Two-Step Fractions
- Two-Step Decimals
- Multi-Step Integers
- Multi-Step with Parentheses
- Multi-Step Rational
- Multi-Step Fractions
- Multi-Step Decimals
- Solve by Factoring
- Completing the Square
- Quadratic Formula
- Biquadratic
- Logarithmic
- Exponential
- Rational Roots
- Floor/Ceiling
- Equation Given Roots
- Substitution
- Elimination
- Cramer's Rule
- Gaussian Elimination
- System of Inequalities
- Perfect Squares
- Difference of Squares
- Difference of Cubes
- Sum of Cubes
- Polynomials
- Distributive Property
- FOIL method
- Perfect Cubes
- Binomial Expansion
- Logarithmic Form
- Absolute Value
- Rational Number
- Partial Fractions
- Is Polynomial
- Leading Coefficient
- Leading Term
- Standard Form
- Complete the Square
- Synthetic Division
- Linear Factors
- Rationalize Denominator
- Rationalize Numerator
- Identify Type
- Convergence
- Interval Notation
- Pi (Product) Notation
- Boolean Algebra
- Truth Table
- Mutual Exclusive
- Cardinality
- Caretesian Product
- Age Problems
- Distance Problems
- Cost Problems
- Investment Problems
- Number Problems
- Percent Problems
- Addition/Subtraction
- Multiplication/Division
- Dice Problems
- Coin Problems
- Card Problems
- Pre Calculus
- Linear Algebra
- Trigonometry
- Conversions

Most Used Actions
Number line.
- \left|3x+1\right|=4
- \left|a-6\right|=\left|6-a\right|
- 1.5\left|3p\right|=4.5
- 4\left|2x-8\right|=9
- \left|3x+4\right|=-3
- 5-\left|2(x+3)\right|=0
absolute-equation-calculator
- High School Math Solutions – Absolute Value Equation Calculator Solving absolute value equations is somewhat tricky; it requires understanding of the absolute value property.... Read More
Absolute Value Equation Calculator
What do you want to calculate.
- Solve for Variable
- Practice Mode
- Step-By-Step
Example (Click to try)
About absolute value equations.
- Get the absolve value expression by itself.
- Set up two equations and solve them separately.
Absolute Value Equation Video Lesson
- Khan Academy Video: Absolute Value Equations
Need more problem types? Try MathPapa Algebra Calculator
Clear Absolute Value Equation Calculator »

How to solve absolute value equations
|x + 5| = 3.
Worksheet on Abs Val Equations Abs Val Eqn Solver
The General Steps to solve an absolute value equation are:
- Rewrite the absolute value equation as two separate equations, one positive and the other negative
- Solve each equation separately
- After solving, substitute your answers back into original equation to verify that you solutions are valid
- Write out the final solution or graph it as needed
It's always easiest to understand a math concept by looking at some examples so, check outthe many examples and practice problems below.
You can always check your work with our Absolute value equations solver too
Practice Problems
Example equation.
Solve the equation: | X + 5| = 3
Click here to practice more problems like this one , questions that involve variables on 1 side of the equation.
Some absolute value equations have variables both sides of the equation. However, that will not change the steps we're going to follow to solve the problem as the example below shows:
Solve the equation: |3 X | = X − 21
Solve the following absolute value equation: | 5X +20| = 80
Solve the following absolute value equation: | X | + 3 = 2 X
This first set of problems involves absolute values with x on just 1 side of the equation (like problem 2 ).
Solve the following absolute value equation: |3 X −6 | = 21
Ultimate Math Solver (Free) Free Algebra Solver ... type anything in there!
Popular pages @ mathwarehouse.com.

- EXPLORE Random Article
How to Solve Absolute Value Equations
Last Updated: January 31, 2023 References
This article was co-authored by wikiHow Staff . Our trained team of editors and researchers validate articles for accuracy and comprehensiveness. wikiHow's Content Management Team carefully monitors the work from our editorial staff to ensure that each article is backed by trusted research and meets our high quality standards. This article has been viewed 23,117 times.

Setting up the Problem

- For example, |9| = 9; |-9| = -(-9) = 9.

Calculating the Values

Check Your Work

Expert Q&A
Video . by using this service, some information may be shared with youtube..
- Remember that absolute value bars are distinct from parentheses and function differently. Thanks Helpful 0 Not Helpful 0
- Once you've solved for any variables, remember to simplify absolute values accordingly. Thanks Helpful 0 Not Helpful 0
You Might Also Like

- ↑ http://tutorial.math.lamar.edu/Classes/Alg/SolveAbsValueEqns.aspx
- ↑ https://www.mathsisfun.com/numbers/absolute-value.html
- ↑ http://www.varsitytutors.com/high_school_math-help/solving-absolute-value-equations
- ↑ http://www.purplemath.com/modules/solveabs.htm
- ↑ https://www.khanacademy.org/math/algebra/absolute-value-equations-functions/absolute-value-equations/v/absolute-value-equations
About this article

To solve absolute value equations, first isolate the absolute value terms by moving anything outside of the vertical bars to the other side of the equation. Next, solve for the positive value of the equation by isolating the variable. Since the absolute variable can represent 2 numbers, then solve for the negative value by putting a negative sign outside the vertical bars. Then, move the negative by dividing both sides by -1 and solve for the variable. If you want to learn how to check your answers for an absolute value equation, keep reading the article! Did this summary help you? Yes No
Did this article help you?

- About wikiHow
- Terms of Use
- Privacy Policy
- Do Not Sell or Share My Info
- Not Selling Info
The solvers module in SymPy implements methods for solving equations.
It is recommended to use solveset() to solve univariate equations and sympy.solvers.solveset.linsolve() to solve system of linear equations instead of solve() , since sooner or later the solveset will take over solve either internally or externally.
Algebraic equations ¶
Use solve() to solve algebraic equations. We suppose all equations are equaled to 0, so solving x**2 == 1 translates into the following code:
The first argument for solve() is an equation (equaled to zero) and the second argument is the symbol that we want to solve the equation for.
Algebraically solves equations and systems of equations.
- polynomial,
- transcendental
- piecewise combinations of the above
- systems of linear and polynomial equations
- sytems containing relational expressions.
Input is formed as:
- a single Expr or Poly that must be zero,
- an Equality
- a Relational expression or boolean
iterable of one or more of the above
- 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])
return list (perhaps empty) of solution mappings
return list of symbols and set of tuple(s) of solution(s)
don’t try to solve for any of the free symbols in exclude; if expressions are given, the free symbols in them will be extracted automatically.
If False, don’t do any testing of solutions. This can be useful if one wants to include solutions that make any denominator zero.
do a fast numerical check if f has only one symbol.
a very fast, minimal testing.
show a warning if checksol() could not conclude.
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
make positive all symbols without assumptions regarding sign.
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.
do not use the polys/matrix method to solve a system of equations, solve them one at a time as you might “manually”
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, ....
instructs solve to try to find a particular solution to a linear system with as many zeros as possible; this is very expensive
when using particular=True, use a fast heuristic instead to find a solution with many zeros (instead of using the very slow method guaranteed to find the largest number of zeros possible)
return explicit solutions when cubic expressions are encountered
return explicit solutions when quartic expressions are encountered
return explicit solutions (if possible) when quintic expressions are encountered
solve() with check=True (default) will run through the symbol tags to elimate unwanted solutions. If no assumptions are included all possible solutions will be returned.
By using the positive tag only one solution will be returned:
Assumptions aren’t checked when \(solve()\) input involves relationals or bools.
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:
If check=False then a solution to the numerator being zero is found: x = 0. In this case, this is a spurious solution since sin(x)/x has the well known limit (without dicontinuity) of 1 at x = 0:
In the following case, however, the limit exists and is equal to the the value of x = 0 that is excluded when check=True:
The output varies according to the input and can be seen by example:
boolean or univariate Relational
to always get a list of solution mappings, use flag dict=True
to get a list of symbols and set of solution(s) use flag set=True
single expression and single symbol that is in the expression
single expression with no symbol that is in the expression
single expression with no symbol given
In this case, all free symbols will be selected as potential symbols to solve for. If the equation is univariate then a list of solutions is returned; otherwise – as is the case when symbols are given as an iterable of length > 1 – a list of mappings will be returned. >>> solve ( x - 3 ) [3] >>> solve ( x ** 2 - y ** 2 ) [{x: -y}, {x: y}] >>> solve ( z ** 2 * x ** 2 - z ** 2 * y ** 2 ) [{x: -y}, {x: y}, {z: 0}] >>> solve ( z ** 2 * x - z ** 2 * y ** 2 ) [{x: y**2}, {z: 0}]
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 one 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.
>>> 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)], set([(-sqrt(-x),), (sqrt(-x),)])) >>> from sympy import Indexed , IndexedBase , Tuple , sqrt >>> 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 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 that can be targeted with 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 - 6 + 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] To solve for a function within a derivative, use dsolve.
single expression and more than 1 symbol
when there is a linear solution >>> solve ( x - y ** 2 , x , y ) [{x: y**2}] >>> solve ( x ** 2 - y , x , y ) [{y: x**2}] when undetermined coefficients are identified that are linear >>> solve (( a + b ) * x - b + 2 , a , b ) {a: -2, b: 2} that are nonlinear >>> solve (( a + b ) * x - b ** 2 + 2 , a , b , set = True ) ([a, b], set([(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))]))
if there is no linear solution then the first successful attempt for a nonlinear solution will be returned
involving relationals or bools >>> solve ([ x < 3 , x - 2 ]) Eq(x, 2) >>> solve ([ x > 3 , x - 2 ]) False when the system is linear with a solution >>> solve ([ x - 3 ], x ) {x: 3} >>> solve (( x + 5 * y - 2 , - 3 * x + 6 * y - 15 ), x , y ) {x: -3, y: 1} >>> solve (( x + 5 * y - 2 , - 3 * x + 6 * y - 15 ), x , y , z ) {x: -3, y: 1} >>> solve (( x + 5 * y - 2 , - 3 * x + 6 * y - z ), z , x , y ) {x: -5*y + 2, z: 21*y - 6} without a solution >>> solve ([ x + 3 , x - 3 ]) []
when the system is not linear
if no symbols are given, all free symbols will be selected and a list of mappings returned
if any equation doesn’t 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
Disabling High-order, Explicit Solutions
When solving polynomial expressions, one 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:
Solving Equations Involving Radicals
Because of SymPy’s use of the principle root (issue #8789), some solutions to radical equations will be missed unless check=False:
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*_p**5 - 7*_p**3 + 1, 1)**15, CRootOf(7*_p**5 - 7*_p**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:
We will construct a known value for this expression at x = 3 by selecting the 1-th root for each radical:
The solve function is unable to find any exact roots to this equation:
The function unrad, however, can be used to get a form of the equation for which numerical roots can be found:
Although eq or eq1 could have been used to find xvals, the solution can only be verified with expr1:
Return a tuple derived from f = lhs - rhs that is one of the following:
(0, 1) meaning that f is independent of the symbols in symbols that aren’t in exclude , e.g: >>> from sympy.solvers.solvers import solve_linear >>> from sympy.abc import x , y , z >>> from sympy import cos , sin >>> 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) (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).
The variable x appears as a linear variable in each of the following:
When not linear in x or y then the numerator and denominator are returned.
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:
But automatic rewriting may cause a symbol in the denominator to appear in the numerator so a solution will be returned:
Use an unevaluated expression to avoid this:
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.
A list of symbols for which a solution is desired may be given:
A list of symbols to ignore may also be given:
(A solution for y is obtained because it is the first variable from the canonically sorted list of symbols that had a linear solution.)
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. 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 functions is a Nx(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.
Solve the following system:
A degenerate system returns an empty dictionary.
Solves the augmented matrix system using LUsolve and returns a dictionary in which solutions are keyed to the symbols of syms as ordered .
The matrix must be invertible.
sympy.matrices.LUsolve
Solve equation of a type p(x; a_1, ..., a_k) == q(x) where both p, q are univariate polynomials and f depends on k parameters. The result of this functions is a dictionary with symbolic values of those parameters with respect to coefficients in q.
This functions accepts both Equations class instances and ordinary SymPy expressions. Specification of parameters and variable is obligatory for efficiency and simplicity reason.
Solve a nonlinear equation system numerically:
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.
Overdetermined systems are supported.
For one-dimensional functions the syntax is simplified:
mpmath.findroot is used, you can find there more extensive documentation, especially concerning keyword parameters and available solvers. Note, however, that this routine works only with the numerator of the function in the one-dimensional case, and for very steep functions near the root this may lead to a failure in the verification of the root. In this case you should use the flag \(verify=False\) and independently verify the solution.
One might safely skip the verification if bounds of the root are known and a bisection method is used:
Checks whether expression \(expr\) satisfies all assumptions.
\(assumptions\) is a dict of assumptions: {‘assumption’: True|False, ...}.
\(None\) is returned if check_assumptions() could not conclude.
Checks whether sol is a solution of equation f == 0.
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.
To check if an expression is zero using checksol, pass it as f and send an empty dictionary for symbol :
None is returned if checksol() could not conclude.
Ordinary Differential equations (ODEs) ¶
Partial differential equations (pdes) ¶, deutils (utilities for solving ode’s and pde’s) ¶.
Returns the order of a given differential equation with respect to func.
This function is implemented recursively.
Recurrence Equations ¶
Solve univariate recurrence with rational coefficients.
Given \(k\) -th order linear recurrence \(\operatorname{L} y = f\) , or equivalently:
where \(a_{i}(n)\) , for \(i=0, \dots, k\) , are polynomials or rational functions in \(n\) , and \(f\) is a hypergeometric function or a sum of a fixed number of pairwise dissimilar hypergeometric terms in \(n\) , finds all solutions or returns None , if none were found.
Initial conditions can be given as a dictionary in two forms:
{ n_0 : v_0, n_1 : v_1, ..., n_m : v_m } { y(n_0) : v_0, y(n_1) : v_1, ..., y(n_m) : v_m }
or as a list L of values:
L = [ v_0, v_1, ..., v_m ]
where L[i] = v_i , for \(i=0, \dots, m\) , maps to \(y(n_i)\) .
rsolve_poly , rsolve_ratio , rsolve_hyper
Lets consider the following recurrence:
Given linear recurrence operator \(\operatorname{L}\) of order \(k\) with polynomial coefficients and inhomogeneous equation \(\operatorname{L} y = f\) , where \(f\) is a polynomial, we seek for all polynomial solutions over field \(K\) of characteristic zero.
The algorithm performs two basic steps:
Compute degree \(N\) of the general polynomial solution. Find all polynomials of degree \(N\) or less of \(\operatorname{L} y = f\) .
There are two methods for computing the polynomial solutions. If the degree bound is relatively small, i.e. it’s smaller than or equal to the order of the recurrence, then naive method of undetermined coefficients is being used. This gives system of algebraic equations with \(N+1\) unknowns.
In the other case, the algorithm performs transformation of the initial equation to an equivalent one, for which the system of algebraic equations has only \(r\) indeterminates. This method is quite sophisticated (in comparison with the naive one) and was invented together by Abramov, Bronstein and Petkovsek.
It is possible to generalize the algorithm implemented here to the case of linear q-difference and differential equations.
Lets say that we would like to compute \(m\) -th Bernoulli polynomial up to a constant. For this we can use \(b(n+1) - b(n) = m n^{m-1}\) recurrence, which has solution \(b(n) = B_m + C\) . For example:
Given linear recurrence operator \(\operatorname{L}\) of order \(k\) with polynomial coefficients and inhomogeneous equation \(\operatorname{L} y = f\) , where \(f\) is a polynomial, we seek for all rational solutions over field \(K\) of characteristic zero.
This procedure accepts only polynomials, however if you are interested in solving recurrence with rational coefficients then use rsolve which will pre-process the given equation and run this procedure with polynomial arguments.
Compute polynomial \(v(n)\) which can be used as universal denominator of any rational solution of equation \(\operatorname{L} y = f\) . Construct new linear difference equation by substitution \(y(n) = u(n)/v(n)\) and solve it for \(u(n)\) finding all its polynomial solutions. Return None if none were found.
Algorithm implemented here is a revised version of the original Abramov’s algorithm, developed in 1989. The new approach is much simpler to implement and has better overall efficiency. This method can be easily adapted to q-difference equations case.
Besides finding rational solutions alone, this functions is an important part of Hyper algorithm were it is used to find particular solution of inhomogeneous part of a recurrence.
rsolve_hyper
Given linear recurrence operator \(\operatorname{L}\) of order \(k\) with polynomial coefficients and inhomogeneous equation \(\operatorname{L} y = f\) we seek for all hypergeometric solutions over field \(K\) of characteristic zero.
The inhomogeneous part can be either hypergeometric or a sum of a fixed number of pairwise dissimilar hypergeometric terms.
The algorithm performs three basic steps:
Group together similar hypergeometric terms in the inhomogeneous part of \(\operatorname{L} y = f\) , and find particular solution using Abramov’s algorithm. Compute generating set of \(\operatorname{L}\) and find basis in it, so that all solutions are linearly independent. Form final solution with the number of arbitrary constants equal to dimension of basis of \(\operatorname{L}\) .
Term \(a(n)\) is hypergeometric if it is annihilated by first order linear difference equations with polynomial coefficients or, in simpler words, if consecutive term ratio is a rational function.
The output of this procedure is a linear combination of fixed number of hypergeometric terms. However the underlying method can generate larger class of solutions - D’Alembertian terms.
Note also that this method not only computes the kernel of the inhomogeneous equation, but also reduces in to a basis so that solutions generated by this procedure are linearly independent
Systems of Polynomial Equations ¶
Solve a system of polynomial equations.
Solve a polynomial system using Gianni-Kalkbrenner algorithm.
The algorithm proceeds by computing one Groebner basis in the ground domain and then by iteratively computing polynomial factorizations in appropriately constructed algebraic extensions of the ground domain.
1. Patrizia Gianni, Teo Mora, Algebraic Solution of System of Polynomial Equations using Groebner Bases, AAECC-5 on Applied Algebra, Algebraic Algorithms and Error-Correcting Codes, LNCS 356 247–257, 1989
Diophantine Equations (DEs) ¶
See Diophantine
Inequalities ¶
See Inequality Solvers

Table Of Contents
- Algebraic equations
- Ordinary Differential equations (ODEs)
- Partial Differential Equations (PDEs)
- Deutils (Utilities for solving ODE’s and PDE’s)
- Recurrence Equations
- Systems of Polynomial Equations
- Diophantine Equations (DEs)
- Inequalities
Related Topics
- Previous: PDE
- Next: Diophantine
- Show Source
Quick search
- SymPy Tutorial: Solvers »
The solvers module in SymPy implements methods for solving equations.
It is recommended to use solveset() to solve univariate equations, sympy.solvers.solveset.linsolve() to solve system of linear equations instead of solve() and sympy.solvers.solveset.nonlinsolve() to solve system of non linear equations since sooner or later the solveset will take over solve either internally or externally.
Algebraic equations �
Use solve() to solve algebraic equations. We suppose all equations are equaled to 0, so solving x**2 == 1 translates into the following code:
The first argument for solve() is an equation (equaled to zero) and the second argument is the symbol that we want to solve the equation for.
Algebraically solves equations and systems of equations.
- polynomial,
- transcendental
- piecewise combinations of the above
- systems of linear and polynomial equations
- systems containing relational expressions.
Input is formed as:
- a single Expr or Poly that must be zero,
- an Equality
- a Relational expression or boolean
iterable of one or more of the above
- 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)' don't 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, don't do any testing of solutions. This can be useful if one wants 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, ... . '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)' when using particular=True, use a fast heuristic instead to find a solution with many zeros (instead of using the very slow method guaranteed to find the largest number of zeros possible) 'cubics=True (default)' return explicit solutions when cubic expressions are encountered 'quartics=True (default)' return explicit solutions when quartic expressions are encountered 'quintics=True (default)' return explicit solutions (if possible) when quintic expressions are encountered
solve() with check=True (default) will run through the symbol tags to elimate unwanted solutions. If no assumptions are included all possible solutions will be returned.
By using the positive tag only one solution will be returned:
Assumptions aren't checked when \(solve()\) input involves relationals or bools.
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:
If check=False then a solution to the numerator being zero is found: x = 0. In this case, this is a spurious solution since sin(x)/x has the well known limit (without dicontinuity) of 1 at x = 0:
In the following case, however, the limit exists and is equal to the the value of x = 0 that is excluded when check=True:
The output varies according to the input and can be seen by example:
boolean or univariate Relational
to always get a list of solution mappings, use flag dict=True
to get a list of symbols and set of solution(s) use flag set=True
single expression and single symbol that is in the expression
single expression with no symbol that is in the expression
single expression with no symbol given
In this case, all free symbols will be selected as potential symbols to solve for. If the equation is univariate then a list of solutions is returned; otherwise -- as is the case when symbols are given as an iterable of length > 1 -- a list of mappings will be returned. >>> solve ( x - 3 ) [3] >>> solve ( x ** 2 - y ** 2 ) [{x: -y}, {x: y}] >>> solve ( z ** 2 * x ** 2 - z ** 2 * y ** 2 ) [{x: -y}, {x: y}, {z: 0}] >>> solve ( z ** 2 * x - z ** 2 * y ** 2 ) [{x: y**2}, {z: 0}]
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 one 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.
>>> 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 , sqrt >>> 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 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 that can be targeted with 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 - 6 + 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] To solve for a function within a derivative, use dsolve.
single expression and more than 1 symbol
when there is a linear solution >>> solve ( x - y ** 2 , x , y ) [{x: y**2}] >>> solve ( x ** 2 - y , x , y ) [{y: x**2}] when undetermined coefficients are identified that are linear >>> solve (( a + b ) * x - b + 2 , a , b ) {a: -2, b: 2} that are nonlinear >>> solve (( a + b ) * x - b ** 2 + 2 , a , b , set = True ) ([a, b], {(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))})
if there is no linear solution then the first successful attempt for a nonlinear solution will be returned
involving relationals or bools >>> solve ([ x < 3 , x - 2 ]) Eq(x, 2) >>> solve ([ x > 3 , x - 2 ]) False when the system is linear with a solution >>> solve ([ x - 3 ], x ) {x: 3} >>> solve (( x + 5 * y - 2 , - 3 * x + 6 * y - 15 ), x , y ) {x: -3, y: 1} >>> solve (( x + 5 * y - 2 , - 3 * x + 6 * y - 15 ), x , y , z ) {x: -3, y: 1} >>> solve (( x + 5 * y - 2 , - 3 * x + 6 * y - z ), z , x , y ) {x: -5*y + 2, z: 21*y - 6} without a solution >>> solve ([ x + 3 , x - 3 ]) []
when the system is not linear
if no symbols are given, all free symbols will be selected and a list of mappings returned
if any equation doesn't 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
Disabling High-order, Explicit Solutions
When solving polynomial expressions, one 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:
Solving Equations Involving Radicals
Because of SymPy's use of the principle root (issue #8789), some solutions to radical equations will be missed unless check=False:
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*_p**5 - 7*_p**3 + 1, 1)**15, CRootOf(7*_p**5 - 7*_p**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:
We will construct a known value for this expression at x = 3 by selecting the 1-th root for each radical:
The solve function is unable to find any exact roots to this equation:
The function unrad, however, can be used to get a form of the equation for which numerical roots can be found:
Although eq or eq1 could have been used to find xvals, the solution can only be verified with expr1:
Return a tuple derived from f = lhs - rhs that is one of the following:
(0, 1) meaning that f is independent of the symbols in symbols that aren't in exclude , e.g: >>> from sympy.solvers.solvers import solve_linear >>> from sympy.abc import x , y , z >>> from sympy import cos , sin >>> 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) (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).
The variable x appears as a linear variable in each of the following:
When not linear in x or y then the numerator and denominator are returned.
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:
But automatic rewriting may cause a symbol in the denominator to appear in the numerator so a solution will be returned:
Use an unevaluated expression to avoid this:
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.
A list of symbols for which a solution is desired may be given:
A list of symbols to ignore may also be given:
(A solution for y is obtained because it is the first variable from the canonically sorted list of symbols that had a linear solution.)
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. 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 functions is a Nx(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.
Solve the following system:
A degenerate system returns an empty dictionary.
Solves the augmented matrix system using LUsolve and returns a dictionary in which solutions are keyed to the symbols of syms as ordered .
The matrix must be invertible.
sympy.matrices.LUsolve
Solve equation of a type p(x; a_1, ..., a_k) == q(x) where both p, q are univariate polynomials and f depends on k parameters. The result of this functions is a dictionary with symbolic values of those parameters with respect to coefficients in q.
This functions accepts both Equations class instances and ordinary SymPy expressions. Specification of parameters and variable is obligatory for efficiency and simplicity reason.
Solve a nonlinear equation system numerically:
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 consistency 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.
For one-dimensional functions the syntax is simplified:
To solve with higher precision than the default, use the prec argument.
To solve for complex roots of real functions, a nonreal initial point must be specified:
mpmath.findroot is used and you can find there 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.
One might safely skip the verification if bounds of the root are known and a bisection method is used:
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.
Checks whether expression \(expr\) satisfies all assumptions.
\(assumptions\) is a dict of assumptions: {'assumption': True|False, ...}.
To check assumptions of expr against another variable or expression, pass the expression or variable as against .
\(None\) is returned if check_assumptions() could not conclude.
Checks whether sol is a solution of equation f == 0.
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.
To check if an expression is zero using checksol, pass it as f and send an empty dictionary for symbol :
None is returned if checksol() could not conclude.
Ordinary Differential equations (ODEs) �
Partial differential equations (pdes) �, deutils (utilities for solving ode's and pde's) �.
Returns the order of a given differential equation with respect to func.
This function is implemented recursively.
Recurrence Equations �
Solve univariate recurrence with rational coefficients.
Given \(k\) -th order linear recurrence \(\operatorname{L} y = f\) , or equivalently:
where \(a_{i}(n)\) , for \(i=0, \ldots, k\) , are polynomials or rational functions in \(n\) , and \(f\) is a hypergeometric function or a sum of a fixed number of pairwise dissimilar hypergeometric terms in \(n\) , finds all solutions or returns None , if none were found.
Initial conditions can be given as a dictionary in two forms:
{ n_0 : v_0, n_1 : v_1, ..., n_m : v_m } { y(n_0) : v_0, y(n_1) : v_1, ..., y(n_m) : v_m }
or as a list L of values:
L = [ v_0, v_1, ..., v_m ]
where L[i] = v_i , for \(i=0, \ldots, m\) , maps to \(y(n_i)\) .
rsolve_poly , rsolve_ratio , rsolve_hyper
Lets consider the following recurrence:
Given linear recurrence operator \(\operatorname{L}\) of order \(k\) with polynomial coefficients and inhomogeneous equation \(\operatorname{L} y = f\) , where \(f\) is a polynomial, we seek for all polynomial solutions over field \(K\) of characteristic zero.
The algorithm performs two basic steps:
Compute degree \(N\) of the general polynomial solution. Find all polynomials of degree \(N\) or less of \(\operatorname{L} y = f\) .
There are two methods for computing the polynomial solutions. If the degree bound is relatively small, i.e. it's smaller than or equal to the order of the recurrence, then naive method of undetermined coefficients is being used. This gives system of algebraic equations with \(N+1\) unknowns.
In the other case, the algorithm performs transformation of the initial equation to an equivalent one, for which the system of algebraic equations has only \(r\) indeterminates. This method is quite sophisticated (in comparison with the naive one) and was invented together by Abramov, Bronstein and Petkovsek.
It is possible to generalize the algorithm implemented here to the case of linear q-difference and differential equations.
Lets say that we would like to compute \(m\) -th Bernoulli polynomial up to a constant. For this we can use \(b(n+1) - b(n) = m n^{m-1}\) recurrence, which has solution \(b(n) = B_m + C\) . For example:
Given linear recurrence operator \(\operatorname{L}\) of order \(k\) with polynomial coefficients and inhomogeneous equation \(\operatorname{L} y = f\) , where \(f\) is a polynomial, we seek for all rational solutions over field \(K\) of characteristic zero.
This procedure accepts only polynomials, however if you are interested in solving recurrence with rational coefficients then use rsolve which will pre-process the given equation and run this procedure with polynomial arguments.
Compute polynomial \(v(n)\) which can be used as universal denominator of any rational solution of equation \(\operatorname{L} y = f\) . Construct new linear difference equation by substitution \(y(n) = u(n)/v(n)\) and solve it for \(u(n)\) finding all its polynomial solutions. Return None if none were found.

Algorithm implemented here is a revised version of the original Abramov's algorithm, developed in 1989. The new approach is much simpler to implement and has better overall efficiency. This method can be easily adapted to q-difference equations case.
Besides finding rational solutions alone, this functions is an important part of Hyper algorithm were it is used to find particular solution of inhomogeneous part of a recurrence.
rsolve_hyper
Given linear recurrence operator \(\operatorname{L}\) of order \(k\) with polynomial coefficients and inhomogeneous equation \(\operatorname{L} y = f\) we seek for all hypergeometric solutions over field \(K\) of characteristic zero.
The inhomogeneous part can be either hypergeometric or a sum of a fixed number of pairwise dissimilar hypergeometric terms.
The algorithm performs three basic steps:
Group together similar hypergeometric terms in the inhomogeneous part of \(\operatorname{L} y = f\) , and find particular solution using Abramov's algorithm. Compute generating set of \(\operatorname{L}\) and find basis in it, so that all solutions are linearly independent. Form final solution with the number of arbitrary constants equal to dimension of basis of \(\operatorname{L}\) .
Term \(a(n)\) is hypergeometric if it is annihilated by first order linear difference equations with polynomial coefficients or, in simpler words, if consecutive term ratio is a rational function.
The output of this procedure is a linear combination of fixed number of hypergeometric terms. However the underlying method can generate larger class of solutions - D'Alembertian terms.
Note also that this method not only computes the kernel of the inhomogeneous equation, but also reduces in to a basis so that solutions generated by this procedure are linearly independent
Systems of Polynomial Equations �
Solve a system of polynomial equations.
Solve a polynomial system using Gianni-Kalkbrenner algorithm.
The algorithm proceeds by computing one Groebner basis in the ground domain and then by iteratively computing polynomial factorizations in appropriately constructed algebraic extensions of the ground domain.
1. Patrizia Gianni, Teo Mora, Algebraic Solution of System of Polynomial Equations using Groebner Bases, AAECC-5 on Applied Algebra, Algebraic Algorithms and Error-Correcting Codes, LNCS 356 247--257, 1989
Diophantine Equations (DEs) �
See Diophantine
Inequalities �
See Inequality Solvers

Table Of Contents
- Installation
- SymPy's Architecture
- Basic Operations
- Complex numbers
- Simplification
- Logical Operations
- Algebraic equations
- Ordinary Differential equations (ODEs)
- Partial Differential Equations (PDEs)
- Deutils (Utilities for solving ODE's and PDE's)
- Recurrence Equations
- Systems of Polynomial Equations
- Diophantine Equations (DEs)
- Inequalities
Previous topic
Diophantine
- Show Source
Quick search
- SymPy Tutorial by Vladimir Dobrushkin »

IMAGES
VIDEO
COMMENTS
How to solve absolute value equations using sympy? Ask Question Asked 7 years, 11 months ago Modified 7 years, 11 months ago Viewed 3k times 6 Given the equation |x - 5| + |y| = 5, how can one solve it using SymPy? If I'm using a combination of solve () and Abs () it gives me this error solving Abs (x - 5) when the argument is not real or imaginary
The Python package SymPy can symbolically solve equations, differential equations, linear equations, nonlinear equations, matrix problems, inequalities, Diophantine equations, and evaluate integrals. SymPy can also solve numerically. The Solving Guidance page provides recommendations applicable to many types of solving tasks.
1 Answer Sorted by: 1 This gives [1, -1 + sqrt (2), 1 + sqrt (2)] if you use the current master and manually rewrite the expression as Piecewise. Apparently the rewriting is incomplete when done by solve itself: >>> solve ( (abs ( (abs (x**2-1)-x))-x).rewrite (Piecewise)) [1, -1 + sqrt (2), 1 + sqrt (2)]
The first argument for solve () is an equation (equaled to zero) and the second argument is the symbol that we want to solve the equation for. sympy.solvers.solvers.solve(f, *symbols, **flags) [source] # Algebraically solves equations and systems of equations. Parameters: f : a single Expr or Poly that must be zero an Equality
Solving Functions # There are two high-level functions to solve equations, solve () and solveset (). Here is an example of each: solve () >>> from sympy.abc import x, y >>> from sympy import solve >>> solve(x**2 - y, x, dict=True) [ {x: -sqrt (y)}, {x: sqrt (y)}] solveset ()
SymPy already has a pretty powerful solve function. But it has some deficiencies. For example: It doesn't have a consistent output for various types of solutions It needs to return a lot of types of solutions consistently: Single solution : x = 1 Multiple solutions: x 2 = 1 No Solution: x 2 + 1 = 0; x ∈ R Interval of solution: ⌊ x ⌋ = 0
( (Poly(x), Poly(1, x)), '!='), ... ( (Poly(-x + 1), Poly(1, x)), '>=')]]) Union (Interval.open (-oo, 0), Interval.Lopen (0, 1)) See also solve_poly_inequality sympy.solvers.inequalities.solve_poly_inequality(poly, rel) [source] # Solve a polynomial inequality with rational coefficients. Examples
Parameters: arg : Expr Real or complex expression. Returns: expr : Expr Real part of expression. Examples >>> from sympy import re, im, I, E, symbols >>> x, y = symbols('x y', real=True) >>> re(2*E) 2*E >>> re(2*I + 17) 17 >>> re(2*I) 0 >>> re(im(x) + x*I + 2) 2 >>> re(5 + I + 2) 7 See also im as_real_imag(deep=True, **hints) [source] #
Wiki New issue Solving an equation containing absolute value, with python 3 #17650 Closed andalou opened this issue on Sep 24, 2019 · 3 comments · Fixed by #17767 andalou on Sep 24, 2019 oscarbenjamin added the solvers.solve label on Sep 28, 2019 andalou closed this as completed on Sep 30, 2019 smichr reopened this on Sep 30, 2019
1 Answer Sorted by: 1 You can compute the inner product with the .dot method or with the operator &. For example: BCx2y2 = (AC-AB) & (AC-AB) # or: BCx2y2 = (AC-AB).dot (AC-AB) Just in case you need it, you can also compute the cross product with the .cross method or with the operator ^.
Save to Notebook! Free absolute value equation calculator - solve absolute value equations with all the steps. Type in any equation to get the solution, steps and graph
To solve absolute value equations, find x values that make the expression inside the absolute value positive or negative the constant. To graph absolute value functions, plot two lines for the positive and negative cases that meet at the expression's zero. The graph is v-shaped. Created by Sal Khanand CK-12 Foundation. QuestionsTips & Thanks
What do you want to calculate? Calculate it! Example: 3|2x+1|+4=25 Example (Click to try) 3|2x+1|+4=25 About absolute value equations Solve an absolute value equation using the following steps: Get the absolve value expression by itself. Set up two equations and solve them separately. Absolute Value Equation Video Lesson
Solving Absolute Value Equations. Solving absolute value equations is as easy as working with regular linear equations. The only additional key step that you need to remember is to separate the original absolute value equation into two parts: positive and negative (±) components.Below is the general approach on how to break them down into two equations:
Algebra (all content) 20 units · 412 skills. Unit 1 Introduction to algebra. Unit 2 Solving basic equations & inequalities (one variable, linear) Unit 3 Linear equations, functions, & graphs. Unit 4 Sequences. Unit 5 System of equations. Unit 6 Two-variable inequalities. Unit 7 Functions. Unit 8 Absolute value equations, functions, & inequalities.
The General Steps to solve an absolute value equation are: Rewrite the absolute value equation as two separate equations, one positive and the other negative. Solve each equation separately. After solving, substitute your answers back into original equation to verify that you solutions are valid. Write out the final solution or graph it as needed.
To check your positive equation, plug the value for derived from the positive equation back into the original absolute value equation. If both sides of the equation are equal, the solution is true. For example, if the solution to the positive equation was. x = 1 {\displaystyle x=1} , plug. 1 {\displaystyle 1}
Use solve () to solve algebraic equations. We suppose all equations are equaled to 0, so solving x**2 == 1 translates into the following code: The first argument for solve () is an equation (equaled to zero) and the second argument is the symbol that we want to solve the equation for. Algebraically solves equations and systems of equations.
The first argument for solve() is an equation (equaled to zero) and the second argument is the symbol that we want to solve the equation for. sympy.solvers.solvers.solve (f, *symbols, **flags) [source] Algebraically solves equations and systems of equations. Currently supported are: polynomial, transcendental; piecewise combinations of the above