I am trying to minimize a function in a given interval; in my case the interval is [-pi/2, pi/2].
Here is what I wrote in my script:
ranges = slice(-pi/2, pi/2, pi/200)
res = optimize.brute(g, (ranges,))
with
def g(x):
# z and a are global
(-(z+1) * (((a/4) * (3*cos(x/3) + cos(3*x/2)) +
(b/4) * (-3*sin(x/2)-3*sin(3*x/2)))**2 +
((a/4) * (sin(x/3) + sin(3*x/2)) + (b/4)*
(cos(x/2) + 3*cos(3*x/2)))**2) + 4*(c*cos(x/2))**2)
and the result res is
array([-3.14159265])
The problem I encounter while plotting my solutions is that some of the solutions of the minimization are outside the interval [-pi/2, pi/2]. Any help?
The "problem" is with the default "finishing function": brute has the option of supplying a finishing minimization function. It does this so that the brute force method can be used as a first guess, and then the result can be "polished" using a better minimization function.
If this function is set to None, nothing happens, which is likely what you want here. Unfortunately in this case, the default is set to fmin, which is the downhill simplex (Nelder-Mead) method, and this will simply ignore any range/grid specification. Thus, for a function like sin(0.5 * x), it will start at the lowest point that the brute function found (-pi/2) and continue from there, finding -pi to be the (closest-by) global minimum.
The solution is simple:
res = optimize.brute(g, (ranges,), finish=None)
will give what you want.
Mandatory link to the scipy.optimize.brute documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With