Algebraic equations
SymPy is able to solve algebraic equations with one or several variables. solve(equation, variable) takes as first argument an equation that is supposed to be equaled to 0, and as second argument the variable to solve for. In case of multiple equations and variables, solve returns a dictonary containing the results. Note that SymPy also handles complex numbers using the symbol I.
Code Block |
---|
|
>>> from sympy import *
>>> x = Symbol('x')
>>> solve(x**2 - 1, x)
[-1, 1]
>>> solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y])
{x: -3, y: 1}
>>> solve(Eq(x**4, 1), x)
[-1, 1, -I, I] |
nsolve(function, [variables], x0) is a useful tool to solve nonlinear equation systems numerically, where x0 is a starting vector close to the solution. If there is only one variable, the second argument may be left out.
Code Block |
---|
|
>>> nsolve(sin(x), x, 2)
3.14159265358979
>>> nsolve(sin(x), 2)
3.14159265358979
>>> nsolve(sin(x**2)/(pi - x), x, pi.evalf()/2)
1.77245385090552 |
However, if you would like to compute all solutions to a problem, solvset solveset is the way to go. Considering the difficulty of some of the return values computed by solveset, we highly recommend you to read the official documentation. We will only cover the function brifely, although some more advanced examples will be added to the Exercises and solutions, symbolic mathematics.
Code Block |
---|
|
>>> solveset(x - x, x) # Solving the function x = x for x
S.Complexes |
The return value of solveset is alwyas a Set, in the case above the set class Complexes, which represents the set of all complex numbers,
Another example is :
Code Block |
---|
|
>>> solveset(sin(x), x) # Solving sin(x) = 0 for x
Union(ImageSet(Lambda(_n, 2*_n*pi), Integers), ImageSet(Lambda(_n, 2*_n*pi + pi), Integers)) |
As we can see, the output may seem a bit overwhelming at first. Let's try to interpret it.
"Union" tells us that the answer consists of several independent sets. "ImageSet" is simply a set class, representing the image of a set under a mathematical function. The Lambda function (no good documentation page found) is used in ImageSets to describe the solutions using variables (here "_n"), the functions containing the variables (here "2*_n*pi") and the range appliable to the variables (here the set Integers, representing all integers). All things considered, the returned solution to
is
, which may also be written as