OK, let me first say that if the problem contains the word "stochastic," I probably don't know how it is supposed to work.
Here's how the code works:
f1
gets a random variate, say, alpha
, then calls NMaximize[]
on the function 1. - (Pi - eta)^2 + alpha
. The value of alpha
stays the say during the optimization calculation. The NMaximize
optimizes a quadratic function, whose maximum is obviously when eta == Pi
every time.
f2
, both yours and mine, gets a new random variate every time w[eta]
is evaluated. It is only evaluated when eta
is given a numeric value by NMaximize
. In a single computation NMaximum
does this many times, and each time the value of the variate changes. This random noise makes NMaximum
think there is no convergence.
So back to my ignorance. The approaches are quite different. I don't know which one is correct. It depends on what you are trying to do. So I just fixed the code and left it at that. Optimizing f1
doesn't need NMaximize[]
, so at first I thought that f1
was wrong. But f2
doesn't converge, so maybe that one's wrong. So I leave it to you to decide which does what you intended.
Here's how I would fix the f2
issue. It may be totally wrong for your problem. If the variates have a standard deviation of
$\sigma$, then the precision goal ought to be of a similar order. Here's an example with
$\sigma$ and the precision goal set at
$10^{-3}$:
w[\[Eta]_?NumericQ] :=
Block[{\[Epsilon]}, \[Epsilon] :=
RandomVariate[NormalDistribution[0, 1/1000]];
1.0 - (\[Pi] - \[Eta])^2 + \[Epsilon]];
f2 := NMaximize[{w[\[Eta]], 0. < \[Eta] < 4.}, \[Eta] \[Element]
Reals, Method -> {"DifferentialEvolution",
"RandomSeed" -> RandomInteger[2^63]}, PrecisionGoal -> 3];
Table[f2, {3}]
(*
{{0.999971,
{\[Eta] -> 3.14249}}, {1.00144, {\[Eta] -> 3.14865}}, {1.00111, {\[Eta] -> 3.14819}}}
*)
I got no errors running a few times. It's random noise, so I wouldn't be surprised if it threw an error now and then.
If you need
$\sigma=1$, then set PrecisionGoal
to 1
or less (it must be positive or NMaximize
refuses to compute).