0
$\begingroup$

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:

f[x_,y_]:=NIntegrate[(2y-(x-a/2)^2),{a,0,1}];
FindMaximum[{f[x,0.5],0<x<1},{x,0}]

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:

f[0.2,0.5]

0.9767

Plot[f[x,0.5],{x,0,1}]

enter image description here

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

f[x_,y_?NumericQ]:=NIntegrate[(2y-(x-a/2)^2),{a,0,1}];

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

FindMaximum[{f[x,0.5?NumericQ],0<x<1},{x,0}]

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?

$\endgroup$
2
  • 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
    Commented Jun 2, 2021 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
    Commented Jun 2, 2021 at 22:50

1 Answer 1

1
$\begingroup$

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:

Clear[f];
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:

Clear[f];
f[x_?NumericQ, y_] := NIntegrate[(2 y - (x - a/2)^2), {a, 0, 1}]
$\endgroup$
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
    Commented Jun 3, 2021 at 6:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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