Solutions
Solve the exercises about linear and integer programming.
We'll cover the following...
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:
Let’s break down the most essential details of this code:
-
Line 10: Function
linprogreceives another parameterboundscontaining 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
linprogwith the vector-vsincelinprogsolves a minimization problem and we’re maximizing. Remember the parameterb_ubis expected to be a 1D array, so we need to wrap the limit weight inside an array. The parameterboundsis 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:
...