SymPy allows you to easily solve linear equations as follows:
- Declare variables using the
symbols()function. - Describe the equation in SymPy (transform it so that zero is on the right side).
- Pass the equation and the variable to solve for to the
solve()function. - Display the return value of the
solve()function.
Defining the Equation and Declaring Variables
Describe the equation you want to solve in SymPy and declare the variables you will be using.
from sympy import symbols, solve
# Declare the variable x
x = symbols('x')
# Define the equation 2x + 3 = 7
equation = 2*x + 3 - 7This code does the following:
from sympy import symbols, solve: Imports thesymbolsandsolvefunctions from the SymPy library.symbols('x'): Declares variable x as a SymPy symbol. This allows SymPy to treat x as a mathematical variable rather than just a string.equation = 2*x + 3 - 7: Describes the equation2x + 3 = 7in SymPy. It’s expressed as2x - 4 = 0to have zero on the right side.
# Solve the equation
solution = solve(equation, x)
# Display the solution
print(solution)
This code does the following:
solution = solve(equation, x): Passes the equation you want to solve (equation) and the variable to solve for (x) to thesolve()function. Thesolve()function returns the solutions to the equation as a list.print(solution): Displays the solution.
This result indicates that the solution to the equation 2x + 3 = 7 is x = 2.
A More Complex Example
You can solve equations with fractions or negative numbers as coefficients and constants in a similar way.
from sympy import symbols, solve
# Declare the variable x
x = symbols('x')
# Define the equation -3/2 * x + 5 = 1/4
equation = (-3/2)*x + 5 - (1/4)
# Solve the equation
solution = solve(equation, x)
# Display the solution
print(solution)
# Output [3]