What is SymPy’s .evalf() function?

Sympy, a powerful Python library for symbolic mathematics, offers a myriad of functions to explore and utilize. Among these, the .evalf() method stands out as a key tool for converting symbolic expressions into numerical approximations.

Assume we have a mathematical expression with a π\pi symbol. The .evalf() method takes the symbolic expression and computes an approximation of its numerical value. For example, we have the expression cos(π/4)cos(\pi/4). Without using the .evalf() method, Python would just tell us it's cos(π/4)cos(\pi/4). But when we apply the .evalf() method, it will compute the numerical approximation of this expression, which is approximately 0.707106781186548.

Syntax

Here’s the syntax of the .evalf() method:

sympify(expr).evalf()

Note: sympify(expr) is an expression that we want to convert to its numerical approximations.

Code examples

Let’s see a code example to understand how this method works.

from sympy import *
# Define a symbolic variable
x = symbols('x')
# Define a symbolic expression
expr = cos(pi/4)
# Use .evalf() to get the numerical value
result = expr.evalf()
print(result)
  • Line 3: We define a symbolic variable.

  • Line 6: We define a symbolic expression.

  • Line 9: We use the .evalf() method to get the numerical value.

The .evalf() method computes the numerical approximation for complex numbers as well. Let’s see the code example for complex numbers:

from sympy import *
# Define symbolic variables
z = symbols('z')
# Define the expression
a = 2 + 2*I
b = 2 - 4*I
expr = (a + b)
# Use .evalf() to get the numerical value of the expression
result = expr.evalf()
print("The numerical value of the expression is:", result)

Conclusion

SymPy’s .evalf() function serves as a valuable tool for obtaining numerical approximations of symbolic expressions, including those involving complex numbers.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved