# How to find the critical numbers of a function (in Python, using SymPy)

## Task

When trying to find the maximum and minimum values of a function, one of the main techniques in calculus is to use the “critical numbers” of the function, which are the most important $x$ values to examine to find maxima and minima. Can we find critical numbers for a single-variable function using software?

Related tasks:

## 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

Let’s create an example function to work with.

1
2
3

var( 'x' )
formula = sqrt( x - 1 ) - x
formula

$\displaystyle - x + \sqrt{x - 1}$

Critical numbers come in two kinds. First, where is the derivative zero? Second, where is the derivative undefined but the function is defined?

Let’s begin by finding where the derivative is zero. We’ll use the same techniques introduced in how to write symbolic equations and how to solve symbolic equations.

1
2

derivative = diff( formula )
derivative

$\displaystyle -1 + \frac{1}{2 \sqrt{x - 1}}$

1

solve( Eq( derivative, 0 ) )

$\displaystyle \left[ \frac{5}{4}\right]$

So one critical number, where the derivative is zero, is $x=\frac54$.

Now where is the derivative defined but the function undefined? We compute the domain of both functions and subtract them, using the techniques from how to compute the domain of a function.

1
2
3
4

from sympy.calculus.util import continuous_domain
f_domain = continuous_domain( formula, x, S.Reals )
deriv_domain = continuous_domain( derivative, x, S.Reals )
Complement( f_domain, deriv_domain )

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

So another critical number, where the function is defined but the derivative is not, is $x=1$.

Thus the full set of critical numbers for this function is $\left{1,\frac54\right}$.

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)