2
$\begingroup$

I want to interrupt the optimization of a function when a particular condition is satisfied. Here I provide a test function.

Catch[NMinimize[x^6 + y^4 - 1, {x, y}, Method -> {"RandomSearch"} , 
EvaluationMonitor :> If[x^6 + y^4 - 1 < -0.95, Throw[x]]]]

I would expect the result to be x=..., but Mathematica seems not to evaluate the code and returns just

NMinimize[-1 + x^6 + y^4, {x, y}, Method -> {"RandomSearch"}, 
 EvaluationMonitor :> If[x^6 + y^4 - 1 < -0.95, Throw[x]]]

I am new on Mathematica, so any help would be really appreciated. Thanks.

$\endgroup$
2
  • $\begingroup$ I always have trouble with this - I think it's a bug. You could try this instead: Catch[FindMinimum[X = x; z = x^6 + y^4 - 1, {{x, 1}, {y, 1}}, EvaluationMonitor :> If[z < -0.95, Throw[X]]]] NMinimize doesn't work as well with conditions in the EvaluationMonitor for some reason - probably evaluation order or some interaction with the Method. $\endgroup$
    – flinty
    Commented Jul 6, 2021 at 11:49
  • $\begingroup$ Thank you very much! However, in my actual problem (which involves many variables) I need to find the global minimum of a function, while FindMinimum only gives a local one. I want to use EvaluationMonitor in case the algorithm does not converge, so that I can at least find a good result. But even if you know of any other function doing the same, it would be perfect! $\endgroup$
    – user80883
    Commented Jul 6, 2021 at 13:51

1 Answer 1

1
$\begingroup$

You need to throw and catch with tags here since NMinimize has other throws and catches internally:

Catch[NMinimize[x^6 + y^4 - 1, {x, y}, Method -> {"RandomSearch"}, 
  EvaluationMonitor :> 
   If[x^6 + y^4 - 1 < -0.95, Throw[x, "stop"]]], "stop"]

On a related note: just make it a habit to always use tags when throwing. It's just good practise.

$\endgroup$
1
  • $\begingroup$ Thank you very much! This is exactly what I was looking for. And thanks also for the suggestion! $\endgroup$
    – user80883
    Commented Jul 6, 2021 at 17:16

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.