Solving Math Equations with Python


Solving Math Equations with Python


Solving Equations

Equations and expressions containing symbolic math variables can be solved using SymPy's solve() function




Equations with one solution

SymPy's solve() function can be used to solve simple equations (containing one variable) such as x-4-2=0. The solution is returned in the form of a list when only one value is a part of the solution.

SymPy's solve() function for an expression defined with symbolic math variables is demonstrated by the code below.


from sympy import symbols, solve

x = symbols('x') 
expr = x-4-2

sol = solve(expr)





Regular list indexing can also be used to return the value out a solution list sol as shown in [2].


num = sol[0]





Equations with two solutions

SymPy's solve() function can also be applied to solve equations with two solutions. An example of such an equation is x2−5x+6=0x2−5x+6=0.

The function usually returns the solution as a list.

Written in the code section below is a sample of how an equation with two solutions is solved using SymPy's solve() function.

In [4]:

from sympy import symbols, Eq, solve

y = symbols('x') eq1 = Eq(x*2 -5x + 6)

sol = solve(eq1) 



[2, 3]