Defining Variables

To define variables with SymPy, first import the symbols() function from the SymPy module:


In [1]:
from sympy import symbols

Symbolic math symbols are declared using SymPy's symbols() function. Note that in the arguments of the symbols() function, symbol names are separated by a space (no comma) and surrounded by quotes. The output of the symbols() function are SymPy symbol objects. These output objects need to be separated by comas with no quotation marks.


In [2]:
x, y = symbols('x y')

Substitution

Now that the symbols x and y are instantiated, a symbolic math expression using x and y can be created.

A symbolic math expression is a combination of symbolic math variables with numbers and mathematical opporators (such as +,-,/ and *. The standard Python rules for calculating numbers apply in SymPy symbolic math expressions.


In [3]:
expr = 2*x + y

Use the .subs() method to insert a numerical value into a symbolic math expression, . The first argument of the .subs() method is the variable and the second argument is the numerical value. In the expression above:

$$ 2x +y $$

If we substitute

$$ x = 2 $$

The resulting expression should be

$$ 2(2) + y $$$$ 4 +y $$

In [4]:
expr.subs(x, 2)


Out[4]:
y + 4

The .subs() method does not replace variables in place, it only completes a one-time substitution. If expr is called after the .subs() method is applied, the originol expr expression is returned.


In [5]:
expr


Out[5]:
2*x + y

In order to make the substitution permanent, a new expression object needs to be instantiated as the output of the .subs() method.


In [6]:
expr = 2*x + y
expr2 = expr.subs(x, 2)
expr2


Out[6]:
y + 4

SymPy variables can also be substituted into SymPy expressions


In [7]:
x, y, z = symbols('x y z')
expr = 2*x + y
expr2 = expr.subs(x, z)
expr2


Out[7]:
y + 2*z

More complex substitutions can also be used. Consider the following:

$$ 2x + y $$

substitute in

$$ y = 2x^2 + z^{-3} $$

results in

$$ 2x + 2x^2 + z^{-3} $$

In [8]:
x, y, z = symbols('x y z')
expr = 2*x + y
expr2 = expr.subs(y, 2*x**2 + z**(-3))
expr2


Out[8]:
2*x**2 + 2*x + z**(-3)

A more practical example could involve a large equation and several variable substitutions

$$ n_0e^{-Q_v/RT} $$$$ n_0 = 3.48 \times 10^-6 $$$$ Q_v = 12,700 $$$$ R = 8.31 $$$$ T = 1000 + 273 $$

In [9]:
from sympy import symbols, exp
n0, Qv, R, T = symbols('n0 Qv R T')
expr = n0*exp(-Qv/(R*T))

Multiply SymPy subs() methods can be chained together to substitue multiple variables in one line of code


In [10]:
expr.subs(n0, 3.48e-6).subs(Qv,12700).subs(R, 8031).subs(T, 1000+273)


Out[10]:
3.48e-6*exp(-12700/10223463)

To evaluate an expression as a floating point number, use the .evalf() method.


In [11]:
expr2 = expr.subs(n0, 3.48e-6).subs(Qv,12700).subs(R, 8031).subs(T, 1000+273)

In [12]:
expr2.evalf()


Out[12]:
3.47567968697765e-6

In [ ]: