How to evaluate an algebraic expression in Sympy?
Last Updated :
18 Mar, 2022
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
from sympy.abc import x, y ,z
expression = 4 * x + 5 * y + 6 * z
print (expression.evalf(subs = {x: 1 ,y: 2 ,z: 3 }))
|
Output:
32.0000000000000
In this code, precision is set to 3 digits.
Python3
from sympy.abc import x, y ,z
expression = 4 * x + 5 * y + 6 * z
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
from sympy.abc import *
from sympy import pi
expression = 2 * pi * r
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
from sympy.abc import *
expression = 2 * * x - 4 * y + z
print (expression.subs([(x, 4 ), (y, 2 ), (z, 1 )]))
|
Output:
9
Share your thoughts in the comments
Please Login to comment...