How to write symbolic equations (in Python, using SymPy)
Task
In programming, when we write a=b
, the computer interprets it as
an instruction, to change the value of a
to b
. But in mathematics,
$a=b$ is a statement that $a$ and $b$ are equal; it’s often a starting
point for algebraic work. How can we write a mathematical equation
using software?
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 say we want to write the equation $x^2+y^2=2$.
We must first define $x$ and $y$ as mathematical variables,
then use SymPy’s Eq
function to build an equation.
This helps SymPy distinguish a mathematical equation
from a Python assignment statement.
1
2
var( 'x y' )
Eq( x**2 + y**2, 2 ) # Two parameters: left and right sides of equation
$\displaystyle x^{2} + y^{2} = 2$
You can make a system of equations just by placing several equations in a Python list.
1
2
3
4
5
system = [
Eq( x + 2*y, 1 ),
Eq( x - 9*y, 5 )
]
system
$\displaystyle \left[ x + 2 y = 1, \ x - 9 y = 5\right]$
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)