# Integration in a region?

f[x_, y_] :=  NMinimize[{Sin[a x y], 1 < a < 5}, {a}][[1]]
NIntegrate[If[f[x, y] > 0, 1, 0], {x, 0, 1}, {y, 0, 1}]


I want to perform integration in the rectangular region taking contribution only from those point where $f[x,y]$ is positive.

However, mathematica is not able to compute it.

I tried defining region, but mathematica is giving an error.

region = ImplicitRegion[ NMinimize[{Sin[a x y],
1 < a < 5}, {a}][[1]] >  0, {{x, 0, 1}, {y, 0, 1}}]


Use NumericQ in the definition of f:

Clear[f]
f[x_?NumericQ, y_?NumericQ] := NMinimize[{Sin[a x y], 1 < a < 5}, {a}][[1]]

AbsoluteTiming[
NIntegrate[If[f[x, y] > 0, 1, 0], {x, 0, 1}, {y, 0, 1},
PrecisionGoal -> 2, MaxRecursion -> 3]
]

(* {23.4154, 0.922105} *)

• You can speed up code try:f[x_?NumericQ, y_?NumericQ] := NMinimize[{Sin[a x y], 1 < a < 5}, {a}, Method -> "NelderMead"][[1]]; AbsoluteTiming[ NIntegrate[If[f[x, y] > 0, 1, 0], {x, 0, 1}, {y, 0, 1}, Method -> {Automatic, "SymbolicProcessing" -> 0}]] Jul 1, 2018 at 21:12
• @Mariusz Iwaniuk: "NelderMead" is extremly fast, but evaluates the  integralresult ==1 , all the other methods give ==0.922105 Jul 2, 2018 at 8:19
• @UlrichNeumann. Ok, in this case NelderMead is bad method. Maybe this: f[x_?NumericQ, y_?NumericQ] := NMinimize[{Sin[a x y], 1 < a < 5}, {a}, PrecisionGoal -> 6, Method -> "SimulatedAnnealing"][[1]]; AbsoluteTiming[ NIntegrate[If[f[x, y] > 0, 1, 0], {x, 0, 1}, {y, 0, 1}, PrecisionGoal -> 2, MaxRecursion -> 3]] Jul 2, 2018 at 10:40
• @Mariusz Iwaniuk: Thanks, I was surprised about the outlier "NelderMead" (without warning) Jul 2, 2018 at 11:26
• @MariuszIwaniuk Please consider providing another answer with the observations in the comments here. Jul 2, 2018 at 13:49

I had to write the answer on user's Anton Antonov special request.

We can speed up a little the code by using method SimulatedAnnealing in NMinimize function and adding PrecisionGoal with low value.

f[x_?NumericQ, y_?NumericQ] := NMinimize[{Sin[a x y], 1 < a < 5}, {a},
PrecisionGoal -> 6, Method -> "SimulatedAnnealing"][[1]];

AbsoluteTiming[
NIntegrate[If[f[x, y] > 0, 1, 0], {x, 0, 1}, {y, 0, 1}, PrecisionGoal -> 2,
MaxRecursion -> 3]]

(* {58.8097, 0.922105} *)


Using code user's Anton Antonov on my machine gives output with time:

 (*{192.335, 0.922105}*)


In the comment, what I wrote about method NelderMead in NMinimize.I don't know why gives a incorrect result.

Using information obtained from the book:Mathematica Navigator page: 749

I came to the conclusion, with good starting points NelderMead gives a correct result.

f[x_?NumericQ, y_?NumericQ] :=
NMinimize[{Sin[a x y], 1 < a < 5}, {{a, 4, 5}}, PrecisionGoal -> 6,