Search code examples
pythonlambdascipyscipy-optimizescipy-optimize-minimize

Python: Convert A string of formula to lambda function


I have a string of formula lets said:

str1='(0.5-0.70*x0[0])**2+(0.5-0.70*x0[1])**2'

how can I pass it into lambda function fn Automatically by variable str1

fn= lambda x0: str1


The goal for this is I would like to get a function object:<function main.(x0)> and finally pass it to scipy.optimize.minimize(fn=fn), if you can solve this directly, you can skip the question above


Solution

  • You could use eval():

    from scipy.optimize import minimize
    import numpy as np
    
    str1='(0.5-0.70*x0[0])**2+(0.5-0.70*x0[1])**2'
    
    x0 = np.ones(2)
    
    minimize(lambda x0: eval(str1), x0=x0)