Problem set 1: Solving the consumer problem
In this first problem set, we will take a look at solving the canonical utility maximization problem for the consumer.
Problem set structure:
- Each problem set consists of tasks and problems. Tasks train you in using specific techniques, while problems train you in solving actual economic problems.
- Each problem set also contains solutions, which can be found in separate Python files.
- The Python files
A[..].py
do not run out of the box. But you can copy the code into your notebook or user module. - You should really try to solve the tasks and problems on your own before looking at the answers!
- You goal should, however, not be to write everything from scratch.
- Finding similar code from the lectures and adjusting it is completely ok. I rarely begin completely from scratch, I figure out when I last did something similar and copy in the code to begin with. A quick peak at the solution, and then trying to write the solution yourself is also a very beneficial approach.
Multiple solutions: Within the field of numerical analysis there is often many more than one way of solving a specific problem. So the solution provided is just one example. If you get the same result, but use another approach, that might be just as good (or even better).
Extra problems: Solutions to the extra problems are not provided, but we encourage you to take a look at them if you have the time.
Updating your local version of a notebook.
- 1: Close down all tabs.
- 2: Press the tab Git.
- 3: Press Open Git Repository in Terminal
- 4: Make sure that you are in the repository folder you want to update
exercises-2022
(or your own repo).- On Windows write
cd
. - On Mac write
pwd
. - This will display your current location.
- On Windows write
- 5: See if YOU have any changes
- Write
git status
. - Note if it says
modified: some-file
.
- Write
- 6: View incoming changes
- Write
git fetch
- Write
git diff --name-status main..origin/main
- Write
- 7: Remove conflicting notebooks
- Were any of the files listed in Step 6 also found on the list produced in Step 5? Eg.
02/Primitives.ipynb
in both places? - If there are any overlaps (conflicts), you need to discard your own changes (you'll learn to stash later).
- Of course, if you made notes or experiments that you want to keep, you can always make a copy of your conflicting file and keep that. Just use a good old copy-paste and give your own file a new name.
- Then write
git checkout -- 02/Primitives.ipynb
only if there was a conflict for that file. Do so with all overlapping files.
- Were any of the files listed in Step 6 also found on the list produced in Step 5? Eg.
- 8: Accept incoming changes
- Write
git merge
- Write
Tasks
functions
Implement a Python version of this function:
# write your own code here
Answer: see A1.py
x1_vec = [1.05,1.3,2.3,2.5,3.1]
x2_vec = [1.05,1.3,2.3,2.5,3.1]
Construct a Python function print_table(x1_vec,x2_vec)
to print values of u(x1,x2)
in the table form shown below.
# update this code
def print_table(x1_vec,x2_vec):
# a. empty text
text = ''
# b. top header
text += f'{"":3s}'
for j, x2 in enumerate(x2_vec):
text += f'{j:6d}'
text += '\n' # line shift
# c. body
# missing lines
# d. print
print(text)
Answer: see A2.py
matplotlib
Reproduce the figure below of using the meshgrid
function from numpy and the plot_surface
function from matplotlib.
# import plot modules
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm # for colormaps
# evaluate utility function
x1_grid,x2_grid = np.meshgrid(x1_vec,x2_vec,indexing='ij')
u_grid = u(x1_grid,x2_grid)
# write your code here
Answer: see A3.py
optimize
Consider the following minimization problem:
Solve this problem and illustrate your results.
# update this code
import numpy as np
# a. define function
def f(x):
return 0 # wrong line
# b. solution using a loop
N = 100
x_vec = np.linspace(-10,10,N)
f_vec = np.empty(N)
f_best = np.inf # initial maximum
x_best = np.nan # not-a-number
for i,x in enumerate(x_vec):
f_now = f_vec[i] = f(x)
# missing lines
# c. solution using scipy optmize
from scipy import optimize
x_guess = [0]
# missing line, hint: objective_function = lambda x: ?
# missing line, hint: res = optimize.minimize(?)
# x_best_scipy = res.x[0]
# f_best_scipy = res.fun
# d. print
# missing lines
# e. figure
# missing lines
Answer: see A4.py
Problem
Consider the following -good, , utility maximization problem with exogenous income , and price-vector ,
Problem: Solve the 5-good utility maximization problem for arbitrary preference parameters, , prices and income. First, with a loop, and then with a numerical optimizer.
You can use the following functions:
def utility_function(x,alpha):
# ensure you understand what this function is doing
u = 1
for x_now,alpha_now in zip(x,alpha):
u *= np.max(x_now,0)**alpha_now
return u
def expenditures(x,p):
# ensure you understand what this function is doing
E = 0
for x_now,p_now in zip(x,p):
E += p_now*x_now
return E
def print_solution(x,alpha,I,p):
# you can just use this function
# a. x values
text = 'x = ['
for x_now in x:
text += f'{x_now:.2f} '
text += f']\n'
# b. utility
u = utility_function(x,alpha)
text += f'utility = {u:.3f}\n'
# c. expenditure vs. income
E = expenditures(x,p)
text += f'E = {E:.2f} <= I = {I:.2f}\n'
# d. expenditure shares
e = p*x/I
text += 'expenditure shares = ['
for e_now in e:
text += f'{e_now:.2f} '
text += f']'
print(text)
You can initially use the following parameter choices:
alpha = np.ones(5)/5
p = np.array([1,2,3,4,5])
I = 10
Solving with a loop:
# update this code
N = 15 # number of points in each dimension
fac = np.linspace(0,1,N) # vector betweein 0 and 1
x_max = I/p # maximum x so E = I
# missing lines
for x1 in fac:
for x2 in fac:
for x3 in fac:
for x4 in fac:
for x5 in fac:
x = np.array([x1,x2,x3,x4,x5])*x_max
E = expenditures(x,p)
if E <= I:
u_now = utility_function(x,alpha)
# misssing lines
# print_solution(x_best,alpha,I,p)
Extra: The above code can be written nicer with the
product
function fromitertools
.
Solving with a numerical optimizer:
# update this code
from scipy import optimize
# a. contraint function (negative if violated)
# missing line, hint: constraints = ({'type': 'ineq', 'fun': lambda x: ?})
# missing line, hint: bounds = [(?,?) for p_now in p]
# b. call optimizer
initial_guess = (I/p)/6 # some guess, should be feasible
# missing line, hint: res = optimize.minimize(?,?,method='SLSQP',bounds=bounds,constraints=constraints)
# print(res.message) # check that the solver has terminated correctly
# c. print result
# print_solution(res.x,alpha,I,p)
Solutions using loops
Using raw loops:
See A5.py
Using smart itertools loop:
see A6.py
Solutions using solvers
from scipy import optimize
Solution using a constrained optimizer:
see A7.py
Solution using an unconstrained optimizer:
see A8.py
Extra Problems
Cost minimization
Consider the following 2-good cost minimziation problem with required utility , and price-vector ,
Problem: Solve the 2-good cost-minimization problem with arbitrary required utility, prices and income. Present your results graphically showing that the optimum is a point, where a budgetline is targent to the indifference curve through .
Classy solution
Problem: Implement your solution to the utility maximization problem and/or the cost minimization problem above in a class as seen in Lecture 3.