Link Search Menu Expand Document (external link)

How to compute the domain of a function (in Python, using SymPy)

See all solutions.

Task

Given a mathematical function $f(x)$, we often want to know the set of $x$ values for which the function is defined. That set is called its domain. How can we compute the domain of $f(x)$ using mathematical software?

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 )

$\displaystyle \left(-\infty, -1\right) \cup \left(-1, \infty\right)$

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 )

$\displaystyle \left\{-1\right\}$

The function is undefined only at $x=-1$.

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)