SymPy is a symbolic mathematics Python package. Its goal is to develop into a completely featured computer algebra system while keeping the code as basic as possible to make it understandable and extendable. An algebraic expression is an expression or statement that has been combined using operations like addition, subtraction, division, multiplication, modulus, etc… . for example 10x+2, etc… Let’s demonstrate how to evaluate algebraic expressions in sympy with a few examples. evalf() function and subs() function from sympy is used to evaluate algebraic expressions.
Example 1:
In this example, we import symbols from sympy package. An expression is created and evalf() function is used to evaluate the expression. subs is a parameter in the function, where we pass in a dictionary of symbol mappings to values. In sympy float, precision is up to 15 digits by default. precision can be overridden up to 100 digits.
Python3
# import packages from sympy.abc import x, y ,z # creating an expression expression = 4 * x + 5 * y + 6 * z # evaluating the expression print (expression.evalf(subs = {x: 1 ,y: 2 ,z: 3 })) |
Output:
32.0000000000000
In this code, precision is set to 3 digits.
Python3
# import packages from sympy.abc import x, y ,z # creating an expression expression = 4 * x + 5 * y + 6 * z # evaluating the expression print (expression.evalf( 3 ,subs = {x: 1 ,y: 2 ,z: 3 })) |
Output:
32.0
Example 2:
sympy also has built-in values like pi, which helps us solve numerical problems such as finding the circumference of a circle etc… . precision is set to 10 digits in this example.
Python3
# import packages from sympy.abc import * from sympy import pi # finding the circumference of a circle expression = 2 * pi * r # evaluating the expression print (expression.evalf( 10 ,subs = {r: 2 })) |
Output:
12.56637061
Example 3:
In this example, we use the subs() function to substitute symbols with values, and it evaluates the algebraic expression given. 2**4 -4*2 +1 == 16-8+1 ==9.
Python3
# import packages from sympy.abc import * # creating an expression expression = 2 * * x - 4 * y + z # substituting values in the expression print (expression.subs([(x, 4 ), (y, 2 ), (z, 1 )])) |
Output:
9