How to compute the domain of a function (in Python, using SymPy)
Task
Given a mathematical function
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
We also need to import another tool that SymPy doesn’t pull in by default.
1
from sympy.calculus.util import continuous_domain
We can then ask about a function’s domain. We provide the function, the variable we’re asking about, and the set of numbers we’re working inside of. For a simple one-variable function, we’re typically working in just the real numbers.
1
2
3
var( 'x' )
formula = 1 / ( x + 1 )
continuous_domain( formula, x, S.Reals )
It’s sometimes easier to instead ask where the function is not defined. We can just ask for the complement of the domain.
1
2
domain = continuous_domain( formula, x, S.Reals )
Complement( S.Reals, domain )
The function is undefined only at
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)