fork download
  1. import numpy as np
  2.  
  3. # Coefficients of the objective function (Minimize: 3x1 + 2x2 - 4x3)
  4. c = np.array([3, 2, -4])
  5.  
  6. # Coefficients of the inequality constraints (Ax >= b)
  7. A = np.array([[5, -1, 3],
  8. [-4, 2, 5],
  9. [2, 5, -6]])
  10. b = np.array([8, 4, 5])
  11.  
  12. # Bounds for variables (x1, x2, x3 >= 0)
  13. x_bounds = np.array([0, 0, 0])
  14.  
  15. # Initialize variables with a feasible starting point
  16. x = np.array([1, 1, 1], dtype=float) # Initial guess
  17. alpha = 0.1 # Step size
  18.  
  19. def objective(x):
  20. return np.dot(c, x)
  21.  
  22. def gradient(A, b, x):
  23. return np.dot(A.T, np.linalg.solve(A @ A.T, A @ x - b))
  24.  
  25. # Iterative optimization using gradient descent-like approach
  26. max_iterations = 1000
  27. tolerance = 1e-6
  28.  
  29. for i in range(max_iterations):
  30. grad = gradient(A, b, x)
  31. x_new = x - alpha * grad
  32. x_new = np.maximum(x_new, x_bounds) # Ensure non-negativity
  33.  
  34. if np.linalg.norm(x_new - x) < tolerance:
  35. break
  36. x = x_new
  37.  
  38. # Output results
  39. if np.all(A @ x >= b):
  40. print("Optimal solution found:")
  41. print("x1 =", x[0])
  42. print("x2 =", x[1])
  43. print("x3 =", x[2])
  44. print("Optimal value:", objective(x))
  45. else:
  46. print("The problem is unbounded.")
  47.  
Success #stdin #stdout 0.65s 41600KB
stdin
Standard input is empty
stdout
The problem is unbounded.