Wolfram Computation Meets Knowledge

How do I use ?NumericQ to affect order of evaluation?

Read this article in: Deutsch, Español, Français, 日本語, 한국어, Português, Русский, 中文


When using numerical functions such as NIntegrate or NMaximize, order of evaluation is important. Consider the following function called f :

f[a_] := NIntegrate[ (2 - a) Sin[a x], {x, 0, Pi}]

The function f looks like a well-defined function, because it evaluates for numeric values such as f[0.5]. The problem appears when the function f is given a symbol instead of a number:

f[a]
NIntegrate::inumr :  The integrand (2 - a) Sin[a x] has evaluated to non-numerical values for all sampling points in the region with boundaries {{0, Pi}}

Because a is not defined, the Wolfram Language cannot numerically integrate the expression (2 - a) Sin[a x] with respect to x. This is an issue for any function that might evaluate f[a] before providing a value for a. For example, the Wolfram Language cannot numerically maximize the function f:

NMaximize[f[a], a]
NIntegrate::inumr :  The integrand (2 - a) Sin[a x] has evaluated to non-numerical values for all sampling points in the region with boundaries {{0, Pi}}

This code gives the same error message as when just f[a] is evaluated. In this example, f[a] is evaluated before the full NMaximize statement.

To change the order of evaluation, define the function f to only evaluate if it receives a numeric value by using NumericQ and pattern testing. Append the pattern ?NumericQ to the argument of the function f:

Clear[f]
f[a_?NumericQ] := NIntegrate[ (2 - a) Sin[a x], {x, 0, Pi}]

Now evaluating f[a] returns the function unevaluated instead of producing an error message. The Wolfram Language can numerically maximize the new definition of f because the pattern ?NumericQ changes the order of evaluation:

NMaximize[f[a], a]
{3.05716, {a -> 0.581569}}}
Is this article helpful?
Yes
No

Any comments?

Thank you for your feedback.

Submit

Contact Support

Whether you have a question about billing, activation or something more technical, we are ready to help you.

1-800-WOLFRAM (+1-217-398-0700 for international callers)

Customer Support

Monday–Friday
8am–5pm US Central Time

  • Product registration or activation
  • Pre-sales information and ordering
  • Help with installation and first launch

Advanced Technical Support (for eligible customers)

Monday–Thursday
8am–5pm US Central Time

Friday
8:30–10am & 11am–5pm US Central Time

  • Priority technical support
  • Product assistance from Wolfram experts
  • Help with Wolfram Language programming
  • Advanced installation support