0
$\begingroup$
myfunn[x_, y_] := Module[{},
If[x < 5, Return[0]];
   If[x < 10, Return[2]];
   x*y];

I'm unable to find the maximum value of this function over the following range of x: 0<=x<=20 when y=0 using the NMaxValue, NMaximize or FindMaximum commands

NMaximize[{myfunn[x, 0], 0 <= x <= 20}, x]

NMaxValue[{myfunn[x, 0], 0 <= x <= 20}, x]

All of them return 0 while the answer I'm expecting is 2. Is there anyway to get Mathematica to compute the expected answer? Thanks

$\endgroup$
  • $\begingroup$ Does it work if you do Clear[myfunn] followed by the definition myfunn[x_?NumericQ, y_?NumericQ] := ...? Alternatively, use Piecewise instead of If. $\endgroup$ – Roman Apr 6 at 16:01
  • $\begingroup$ Thank you. myfunn[x_?NumericQ, y_?NumericQ] seems to work although I'm not yet sure why (I'm a light Mathematica user) $\endgroup$ – piotrekp2000 Apr 6 at 16:22
  • 1
    $\begingroup$ That's because when you call your function with symbolic arguments, the If statements never get activated. Check: myfunn[x,y] returns x y. $\endgroup$ – Roman Apr 6 at 17:09
  • $\begingroup$ What I meant to say is that in your definition, the argument myfunn[x,0] is immediately simplified to 0 before ever putting a numerical value in for x. The If statements thus never get to see any numerical values for x. $\endgroup$ – Roman Apr 6 at 19:08
  • $\begingroup$ Makes sense, thank you $\endgroup$ – piotrekp2000 Apr 9 at 12:07
1
$\begingroup$
myfunn[x_, y_] = Piecewise[{{0, x < 5}, {2, x < 10}}, x y];

NMaximize[{myfunn[x, 0], 0 <= x <= 20}, x]

{2., {x -> 6.91445}}

NMaxValue[{myfunn[x, 0], 0 <= x <= 20}, x]

2.

$\endgroup$
0
$\begingroup$

try

myfunn[x_, y_] := If[x<5,0,If[x<10,2,x*y]];

NMaxValue[{myfunn[x, 0], 0<=x<=20}, x]  

2

$\endgroup$

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.