TransWikia.com

How to find the maximum of a function given by a string in Python?

Stack Overflow Asked by Ru44Be4N7 on November 4, 2021

I need to extract the maximum of a mathematical expression written in the Python notation (like -2*(x+1)**2) and the point at which it occurs given by a string (that should be introduced by the user).

I could do it using eval or exec but I’m trying to find alternatives to that.

I’ve tried to use scypy to compute the maximum with the following code:

def f(x):   
    return -2*(x+1)**2
exec(cont)
max_x = scipy.optimize.fmin(lambda x: -f(x), 0, disp=False)
print(max_x)

But I can’t figure out how to extract the function on the string and put it on the first line without using exec.

One Answer

I just read you already found eval and exec so this won't be of much help. I'll leave the answer up for others just in case.

You can use the eval function like this to optimize:

from scipy.optimize import minimize


class OptimizeFunction:

    def __init__(self, formula):
        self.formula = formula

    def evaluate(self, x):
        return eval(self.formula)

    def eval_mirrored(self, x):
        return -self.evaluate(x)

    def get_max(self):
        # Use the mirrored function to get the maximum value
        print(minimize(fun=self.eval_mirrored, x0=[0]))


string = '-2*(x+1)**2'
optimize_function = OptimizeFunction(formula=string)
optimize_function.get_max()

Results in:

      fun: 1.1101586378198223e-16
 hess_inv: array([[0.25]])
      jac: array([8.64197602e-13])
  message: 'Optimization terminated successfully.'
     nfev: 9
      nit: 2
     njev: 3
   status: 0
  success: True
        x: array([-1.00000001])

Answered by Nathan on November 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP