Link Search Menu Expand Document (external link)

How to isolate one variable in an equation (in Python, using SymPy)

See all solutions.

Task

Once we’ve expressed an equation or system of equations using the technique from how to write symbolic equations, we often want the software to isolate one variable in terms of all the others.

Related tasks:

Solution

This answer assumes you have imported SymPy as follows.

1
2
from sympy import *                   # load all math functions
init_printing( use_latex='mathjax' )  # use pretty math output

Let’s create an equation with many variables.

1
2
3
var('P V n R T')
ideal_gas_law = Eq( P*V, n*R*T )
ideal_gas_law

$\displaystyle P V = R T n$

To isolate one variable, call the solve function, and pass that variable as the second argument.

1
solve( ideal_gas_law, R )

$\displaystyle \left[ \frac{P V}{T n}\right]$

The brackets surround a list of all solutions—in this case, just one. That solution is that $R=\frac{PV}{Tn}$.

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)