-1

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 

1 Answers1

0

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])
AbbeGijly
  • 1,191
  • 1
  • 4
  • 5
  • Note the starting guess ```0``` is arbitrary. If you had a good guess to start with use that. – AbbeGijly Dec 10 '21 at 18:25
  • Thank you AbbeGijlym, you´ve helped a lot. I only have a couple more questions, how do I make this a one-liner in the return? and how do i make it calculate both functions at the same time? – Andrés Ortega Dec 10 '21 at 18:39
  • @AndrésOrtega You're being really imprecise. What does "how do i[sic] make it calculate both functions at the same time?" Are you wanting to find the minimum of the product of the two functions? Run them in parallel? – user904963 Dec 10 '21 at 19:30
  • @AndrésOrtega : answer updated with one-liner form and one-liner *vector form for your amusement – AbbeGijly Dec 10 '21 at 19:45