1 # coding=utf-8 2 3 from scipy import optimize 4 import numpy as np 5
15 def get(args): 16 a, b, c, d, e, f, g, h = args 17 fun = lambda x:a*x[0]**g+b*x[0]*x[1]+c*x[1]**h+d*x[0]+e*x[1] + f 18 #fun = lambda x:(x[0] - 1) ** h + (x[1] - 2.5) ** h 19 return fun 20 21 22 def con(args): 23 # Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be non-negative 24 x1min, x1max, x2min, x2max = args 25 cons = ({'type': 'ineq', 'fun': lambda x: x[0] - x1min}, 26 {'type': 'ineq', 'fun': lambda x: -x[0] + x1max}, 27 {'type': 'ineq', 'fun': lambda x: x[1] - x2min}, 28 {'type': 'ineq', 'fun': lambda x: -x[1] + x2max}) 29 return cons 30 31 32 if __name__ == "__main__": 33 args = (2, 3, 7, 8, 9, 10, 2, 2) #a, b, c, d, e, f,g,h 34 args1 = (-1000, 1000, -1000, 1000) #x1min, x1max, x2min, x2max 35 x0 = np.asarray((0, 0)) 36 fun = get(args) 37 cons = con(args1) 38 res = optimize.minimize(fun, x0, method='SLSQP', constraints=cons) 39 print(res.fun) 40 print(res.success) 41 print(res.x)