I'm getting non-numerical-evaluation error messages despite not having any symbolic variables in my code.

Here's a MWE representative of what I'm doing:


This results in the following error:

NIntegrate: The integrand 1.-((-(a/2)+x)^2) has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}.

I don't see what the problem is. $f$ is clearly a function of $x$ and $y$ and has no non-numerical parameters. I fact, it seems to behave properly other than when I ask it to find the maximum:




enter image description here

I've tried adding ?NumericQ in the function definition as follows, but I get the same result:


I've also tried adding ?NumericQ to to function arguments when I call the function in the FindMaximum command, again to no avail:


I had a look at this Q&A, but my situation doesn't fall into any of the cases described there.

What's going on?

  • 2
    $\begingroup$ This works for me: Clear[f]; f[x_?NumericQ, y_?NumericQ] := NIntegrate[(2 y - (x - a/2)^2), {a, 0, 1}]; $\endgroup$
    – MelaGo
    Jun 2 at 22:37
  • $\begingroup$ Yeah, that works. I didn't realise ?NumericQ was a per-variable command; I figured adding it once would make it work for all variables of a function. Cheers! (If you can type that as an answer, I can accept that answer.) $\endgroup$
    – Rain
    Jun 2 at 22:50

The problem is that Mathematica tries to evaluate f[x,0.5] before x is defined. This issue is explained clearly in this Wolfram support page.

To force the function to only evaluate if it receives numerical values for both x and y:

f[x_?NumericQ, y_?NumericQ] := NIntegrate[(2 y - (x - a/2)^2), {a, 0, 1}]
FindMaximum[{f[x, 0.5], 0 < x < 1}, {x, 0}]
 (* {0.979167, {x -> 0.25}} *)

In this particular case, you really only need to restrict x:

f[x_?NumericQ, y_] := NIntegrate[(2 y - (x - a/2)^2), {a, 0, 1}]
  • 2
    $\begingroup$ For comparison, f[x_, y_] = Integrate[(2 y - (x - a/2)^2), {a, 0, 1}]; Maximize[f[x, 1/2], x] $\endgroup$
    – Bob Hanlon
    Jun 3 at 6:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.