Solutions
Solve the exercises about linear and integer programming.
Exercise 1: Fractional knapsack
In the fractional knapsack problem, we don’t have to choose the entire item, but we can get a part of it. That way, we aren’t solving an integer problem anymore. The constraints are the same, but the solution is different from the original knapsack problem. In the original version, a solution is a zero or a one for each item, representing whether we take the item or not. Now a solution is a number between zero and one for each item, representing the fraction of that item we take. So the problem can be written as follows:
Let’s see the code:
from scipy.optimize import linprogimport numpy as npN = 5v = np.random.uniform(1, 10, size=N)W = np.random.uniform(1, 10, size=(1,N))w = np.random.uniform(5, 15)# all variables should be between 0 and 1bounds = [(0, 1) for _ in range(N)]# this solves a minimization problem so we use -vsol = linprog(-v, A_ub = W, b_ub=[w], bounds=bounds)print("Number of objects:", N)print("Max weight:", w)print("Weights:", W)print("Values :", v)print("Success:", sol.success)print("Solution:", sol.x)print("Target func:", -sol.fun)
Let’s break down the most essential details of this code:
-
Line 10: Function
linprog
receives another parameterbounds
containing the bounds of each variable. This should be a sequence of tuples of the form , where is the lower bound and is the upper bound. As we have the constraint , we add the tuples for each item. -
Line 13: We call
linprog
with the vector-v
sincelinprog
solves a minimization problem and we’re maximizing. Remember the parameterb_ub
is expected to be a 1D array, so we need to wrap the limit weight inside an array. The parameterbounds
is a sequence of tuples, as explained above. -
Line 17: To get the value of the target function in the solution, we need to multiply by -1 again since we solved the equivalent minimization problem.
Exercise 2: Product mix problem
If we take as the selling price vector and as the total amount of each material, then we can write the mix problem as follows:
...