Mathematica, nested optimization

I want to use the Maximize solution, defined as a function, in another function. Here is an example:

f1[y_] := x /. Last[Maximize[{Sin[xy], Abs[x] <= y}, x]] (* or any other function *) 

This definition is excellent, for example, if I give f1[4] , I get the answer -((3 \[Pi])/8) .

The problem is that when I want to use it in another function, I get an error. For instance:

FindRoot[f1[y] == Pi/4, {y, 1}]

Gives me the following error:

ReplaceAll :: reps: {x} is neither a list of replacement rules, nor a valid dispatch table, and therefore cannot be used for replacement. โ†’

FindRoot :: nlnum: the value of the function {-0.785398+ (x / .x)} is not a list of numbers with sizes {1} in {y} = {1.}. โ†’

I have been struggling with this for several days! Any comments, ideas, help, ... deeply appreciated! Thank you very much!

+6
source share
1 answer

When y not a number, your Maximize cannot be resolved, in which case its Last element is x , so you get this odd error message. You can fix this by clearing the incorrect definition of f1 and creating a new one that only evaluates numeric arguments:

 ClearAll[f1] f1[y_?NumericQ] := x /. Last[Maximize[{Sin[xy], Abs[x] <= y}, x]] FindRoot[f1[y] == \[Pi]/4, {y, 1}] (* {y -> 0.785398} *) 
+3
source

All Articles