### Python SymPy »

My Coding > Programming language > Python > Python libraries and packages > Python SymPy

# Python SymPy

SymPy is a Computer algebra system (CAS) in Python

SymPy will try to find symbolic solution for any algebraic equations, which is possible to solve symbolically, which can be concluded from its name “Symbolic Python” = “SymPy

To solve quadratic equation with symPy, you need to identify the variable with function Symbol() and then simply call for solve()


from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
print(solve(5 * x ** 2 - 2 * x - 3, x)) # [-3/5, 1]

# 5 * x ** 2 + 2 * x + 3 = 0
print(solve(5 * x ** 2 + 2 * x + 3, x)) # [-1/5 - sqrt(14)*I/5, -1/5 + sqrt(14)*I/5]

### Solving Exponential equations

The way of using function solve() is absolutely the same. Answer will be given in symbolic form as well. To convert it to standard numbers it is necessary to convert it to float() format


# 3**(x+2) - 9**x - 20 = 0
res = solve(3 ** (x + 2) - 9 ** x - 20, x)
print(res)                     # [2*log(2)/log(3), log(5)/log(3)]
print([float(_) for _ in res]) # [1.2618595071429148, 1.464973520717927]

## Trigonometric equations

For solving trigonometric equations it is necessary to import trigonommetric functions as well


from sympy import sin, cos, pi

It is important to remember, that for trigonometric equations unlimited number of solutions exists, both these solutions are periodically repeated. SymPy will give you only one solution ant it is your responsibility to remember about all these repetitions.


from sympy.solvers import solve
from sympy import Symbol
from sympy import sin, cos, pi
x = Symbol('x')
# sin(x) + cos(x) = 0
res = solve(sin(x) + cos(x), x)
print(res) # [-pi/4, 3*pi/4]

Not every equation can be solved with SymPy. Some equations have no analytical solution. In this case you will have NotImplementedError

## Simplified SymPy usage

It is possible to use SymPy without declaring the variable. In this case the equation should be quoted:


from sympy.solvers import solve
print(solve('25*x - 5')) # [1/5]

Published: 2021-11-02 09:02:46

### 9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.