# Unable to find maximum value of my custom function

myfunn[x_, y_] := Module[{},
If[x < 5, Return];
If[x < 10, Return];
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

• Does it work if you do Clear[myfunn] followed by the definition myfunn[x_?NumericQ, y_?NumericQ] := ...? Alternatively, use Piecewise instead of If. – Roman Apr 6 at 16:01
• Thank you. myfunn[x_?NumericQ, y_?NumericQ] seems to work although I'm not yet sure why (I'm a light Mathematica user) – piotrekp2000 Apr 6 at 16:22
• That's because when you call your function with symbolic arguments, the If statements never get activated. Check: myfunn[x,y] returns x y. – Roman Apr 6 at 17:09
• 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. – Roman Apr 6 at 19:08
• Makes sense, thank you – piotrekp2000 Apr 9 at 12:07

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.

try

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

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


2