Home > other >  Find a function maximum with scipy.minimize
Find a function maximum with scipy.minimize

Time:12-11

I´ve been asigned to find a given fuction´s maximum with scipy.minimize with the BFGS method using lambda. I´ve already figured out that in order to do that, I need to minimize the -(f) function, but I cannot change the function itself, only the way it´s called in the minimize. Also, the asnwer must be a float.

A abd B are the two functions to maximize

Thanks in advance for the help!!

def A(x):
 return -(x-1)**2

B = lambda x: -(x 2)**4 

#This is where the minimize is called
def argmax(f):
   from scipy.optimize import minimize
   
   return 

CodePudding user response:

Since the A function must be sign inverted, create another function that calls -A(x), for example:

from scipy.optimize import minimize

res = minimize(lambda t: -A(t), 0)
print(res.x[0])

which prints

0.9999999925496535

Similarly B must be flipped so that minimize finds the argmax of B:

res = minimize(lambda t: -A(t), 0)
print(res.x[0])

which prints

-1.987949853410927

Both of these answers are close to correct (expecting 1 and -2), although the result for B has fairly large error of 0.012.

The one-liner form for both maximizations (via minimizations) would be

return minimize(lambda t: -A(t), 0).x[0]

(and similarly for B)

To minimize both functions at the same time, create a function taking a vector:

return minimize(lambda v: -A(v[0])-B(v[1]), [0, 0]).x

which returns:

array([ 0.99999975, -1.98841637])
  • Related