Advertisement
brandblox

numpy lab(18/03/2024)

Mar 17th, 2024
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. #Assignment: Write a Python Program to solve Linear Programming Problem using
  2. #Simplex Method
  3. import numpy as np
  4.  
  5. def simplex_method(A, b, c):
  6.     m, n = A.shape
  7.     # Create the initial tableau
  8.     tableau = np.hstack([A, np.eye(m), b.reshape(-1, 1)])
  9.     tableau = np.vstack([tableau, np.concatenate([c, np.zeros(m + 1)])])
  10.    
  11.     while True:
  12.         # Find the pivot column
  13.         pivot_col = np.argmin(tableau[-1, :-1])
  14.        
  15.         # If all elements in the last row are non-negative, optimal solution found
  16.         if np.all(tableau[-1, :-1] >= 0):
  17.             break
  18.        
  19.         # Find the pivot row
  20.         ratios = tableau[:-1, -1] / tableau[:-1, pivot_col]
  21.         pivot_row = np.argmin(ratios)
  22.        
  23.         # Perform pivot operation
  24.         tableau[pivot_row, :] /= tableau[pivot_row, pivot_col]
  25.        
  26.         for i in range(m + 1):
  27.             if i != pivot_row:
  28.                 tableau[i, :] -= tableau[i, pivot_col] * tableau[pivot_row, :]
  29.    
  30.     return tableau[-1, -1], tableau[-1, :-1]
  31.  
  32. A = np.array([[2, 1], [1, 2]])
  33. b = np.array([4, 3])
  34. c = np.array([-3, -5])
  35.  
  36. optimal_value, optimal_solution = simplex_method(A, b, c)
  37.  
  38. print("Optimal value:", optimal_value)
  39. print("Optimal solution:", optimal_solution)
  40.  
  41. #Output
  42. Optimal value: 8.333333333333334
  43. Optimal solution: [0.         0.         0.33333333 2.33333333]
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement