Advertisement
Guest User

Untitled

a guest
Jul 5th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. '''
  2. This code minimizes x1 * x4 * (x1 + x2 + x3) + x3
  3. s.t. x1 * x2 * x3 * x4 >= 25
  4. s.t. x1^2 + x2^2 + x3^2 + x4^2 = 40
  5. s.t. 1 <= x1,x2,x3,x4,x5 <= 5
  6. '''
  7.  
  8. import numpy as np
  9. from scipy.optimize import minimize
  10.  
  11. # objective function is the literal objective, what you want to achieve
  12. def objective(x):
  13.     x1 = x[0]
  14.     x2 = x[1]
  15.     x3 = x[2]
  16.     x4 = x[3]
  17.     return x1*x4*(x1+x2+x3)+x3
  18.  
  19. def constraint1(x):
  20.     return x[0]*x[1]*x[2]*x[3]-25.0
  21.  
  22. def constraint2(x):
  23.     sum_eq = 40.0
  24.     for i in range(4):
  25.         sum_eq = sum_eq - x[i]**2
  26.     return sum_eq
  27.  
  28. # initial guesses
  29. n = 4
  30. x0 = np.zeros(n)
  31. x0[0] = 1.0
  32. x0[1] = 5.0
  33. x0[2] = 5.0
  34. x0[3] = 1.0
  35.  
  36. # show initial objective
  37. print('Initial Objective: ' + str(objective(x0)))
  38.  
  39. # optimize
  40. b = (1.0,5.0)
  41. bnds = (b, b, b, b)
  42. con1 = {'type': 'ineq', 'fun': constraint1}
  43. con2 = {'type': 'eq', 'fun': constraint2}
  44. cons = ([con1,con2])
  45. solution = minimize(objective,x0,method='SLSQP',\
  46.                     bounds=bnds,constraints=cons)
  47. x = solution.x
  48.  
  49. # show final objective
  50. print('Final Objective: ' + str(objective(x)))
  51.  
  52. # print solution
  53. print('Solution')
  54. print('x1 = ' + str(x[0]))
  55. print('x2 = ' + str(x[1]))
  56. print('x3 = ' + str(x[2]))
  57. print('x4 = ' + str(x[3]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement