Exercises

Table of Contents

1. Week 2

  1. Type the following code into the REPL

    var1 = "a"
    
    var2 = 'b'
    

    What does the code do? Which of the following lines of code are valid and which will give you an error? First think what you expect to happen and then check.

    var1+var2
    
    var1*var2
    
    var1+1
    
    var2+1
    
    var1*1
    
    var2*1
    
    var1^3
    
    var2^3
    
    var1 < "c"
    
    var1 < 'c'
    
    var2 > 'c'
    
    var1*"1+$var2"
    
    var1*"$(1+var2)"
    
    "var1*$(var2)"
    
    "$(var1)*$(var2)"
    
    length(var1)+2
    
    length(var2)+3
    
    [i for i in 1:10]
    
    string("0",join([i for i in 1:9]))
    
    join("0",[i for i in 1:9])
    
    string("0",[i for i in 1:9])
    
    [var1+i for i in 1:5]
    
    [string(var1,i) for i in 1:5]
    
    join([var2+i for i in 1:5])
    
    string(2,pad=4)
    
  2. Using list comprehension create an array that contains all the lower case characters of the alphabet and bind this array to the variable name alphabet. (Hint: Recall that 'a'+0='a', 'a'+1='b' etc.)

    Then create a single string that contains all the letters of the alphabet and bind it to the name alphabetstring. Also create another string variable alphabetcomma that contains all letters of the alphabet separated by comma.

    Next create an array that contains the string "letter number 1 in the alphabet is a" as first element, the string "letter number 2 in the alphabet is b" as its second element and so on until "letter number 26 in the alphabet is z".

  3. Use the string function with the keyword pad as well as a list comprehension and the join function to create a string "101001000100001000001000000100000001". Can you also do it without using pad (and without typing it in digit by digit, of course)?

2. Week 3

  1. Out of how many code blocks does the following code block consist and what does the function move1 do?

    var = "xyz"
    function move1(input)
        output = string(input[2:end],input[1])
        return output
    end
    move1(var)
    
  2. If we add the following to the code of the previous exercise

    function move1(input::Number)
        output = input + 1
        return output
    end
    

    What output do you expect for the following function calls? Think first before trying!

    move1(3)
    move1(3.0)
    move1("3")
    move1("3.0")
    move1('3')
    move1([1, 2, 3])
    
  3. Write a function addfractions(numerator1,denominator1,numerator2,denominator2) that returns the sum of the fractions \(numerator1/denominator1\) and \(numerator2/denominator2\) as \(numeratorSum,denominatorSum\); e.g. addfractions(1,2,1,3) should return \(5,6\) as \(1/2+1/3=5/6\). (Note that you do not have to cancel common multipliers in the result.)
  4. Write a function evaluatef that takes two inputs: (i) another function (that I call f in the following), (ii) a range (e.g. 1:5). The function evaluatef should evaluate f at each point of the range and print the output. For example, if \(f(x)=x^2\), then \(evaluatef(f,1:3)\) should print:

    f(1) equals 1

    f(2) equals 4

    f(3) equals 9

    (Hint: to get the text printed line by line you have to recall what we did last week, namely list comprehension and escape sequences.)

3. Week 4

  1. Use an if condition to write a function that returns the absolute value of a number.
  2. Write a function dotprod that calculates the dot product of two vectors; i.e. dotprod(a,b) where a and b are arrays of \(n\) numbers should return \(a_1*b_1+a_2*b_2+...+a_n*b_n\). For example, dotprod([1,2,3],[0,1,2]) should return 8. (Of course, julia has such a function built in but programming such a function yourself is a nice exercise to see how loops are used.)
  3. In the following we write a function that solves the equation \(f(x)=0\) for some function \(f\). (As an example, suppose we want to know for which value of \(x\) the equation \(3^x=2\) holds, i.e. for which \(x\) we have \(3^x-2=0\). Then the function is \(f(x)=3^x-2\).)

    We will use a method called "bisection". Our function bisect(f,a,b,eps) takes as inputs: (i) the function \(f\) (\(3^x-2\) in our example), (ii) values \(a\) and \(b\) for which we know that \(f(a)\) and \(f(b)\) have opposite signs (e.g. we could use 0 and 1 in our example as we know that \(3^0-2=-1<0\) and \(3^1-2=1>0\)), (iii) a small positive number \(eps\) which is the precision of our solution method, i.e. we consider \(f(x)\) as being zero whenever \(|f(x)|\leq eps\) (for example we could use \(0.0001\) and be satisfied with every \(x\) that yields \(|f(x)|\leq0.0001\) as a solution to our equation).

    The method works as follows: We know that there is an \(x\) between \(a\) and \(b\) such that \(f(x)=0\). Next we check the function value at the midpoint, i.e. \(f((a+b)/2)\). If \(f((a+b)/2)\) has the same sign as \(f(a)\), then \((a+b)/2\) becomes our "new \(a\)" and we know that the \(x\) we are looking for is between \((a+b)/2\) and \(b\). If, however, \(f((a+b)/2)\) has the same sign as \(f(b)\), then \((a+b)/2\) is our "new \(b\)" and we know that the \(x\) we are looking for is between \(a\) and \((a+b)/2\). (In our example, \(3^{1/2}-2=-0.2679...<0\) and therefore we know that the \(x\) is between \(1/2\) and \(1\).) Then we iterate this procedure: In each step we compute \(f((a+b)/2)\) with the current \(a\) and \(b\) and get a new smaller interval in which our \(x\) lies. We stop iterating if \(|f((a+b)/2)|\leq eps\) and return \((a+b)/2\) as the result then.

4. Week 5

  1. A consumer consumes two perfectly divisible goods \(x_1\) and \(x_2\). The price of one unit of good 1 is 1 while the price of one unit of good 2 is 2. The utility function of the consumer is \(u(x_1,x_2)=x_1^{1/2}x_2^{1/2}\) and his income is 12. Use julia to solve the consumers utility maximization problem, i.e. how many units of each good will the consumer consume? What is his utility level?
  2. Using the previous exercise and your results from there: plot the budget line and the indifference curve at maximal utility level of the consumer in a graph. (Hint: write down the functional equation of the indifference curve and the budget line by hand first.)
  3. Write a function that takes the filename of a text file as input and returns how often the letter 'z' is used in this text file. Download the file pg7207.txt (which contains the text of the book "Menschliches, Allzumenschliches" by F.W. Nietzsche as provided by Project Gutenberg) and count the number of 'z' in there.
  4. Generalize your function from the previous exercise such that it takes two arguments as input: the filename and the letter that should be counted (i.e. the new function cannot only count how many 'z' there are but how many 'a', 'b' etc. there are). If you have managed that, you may want to generalize further: the actual text of the book starts in our file only in line 50 and ends in line 11500. Write a function that takes the range of lines in which the counting should take place as an additional input.

5. Week 6

  1. Let market demand be \(D(p)=10-p\) if \(p<10\) and \(D(p)=0\) if \(p\geq10\). Let market supply be \(S(p)=2p-2\) if \(p>1\) and 0 else. Use the julia Roots.jl package to compute the market equilibrium (price and quantity). (Hint: Market equilibrium occurs where the difference between demand and supply is zero.) Plot supply and demand to verify your result graphically.
  2. Recall that the expected value of a continuously distributed random variable is calculated as \(\int_a^b xf(x)\,dx\) where \(f\) is the density of the random variable and \([a,b]\) is the support of the distribution (i.e. the density of the random variable is 0 outside the interval \([a,b]\)). Consider a random variable with triangular density namely \(f(x)=2x\) for \(x\in[0,1]\) and \(f(x)=0\) for \(x\not\in[0,1]\) and use integration with the QuadGK.jl package to compute its expected value.
  3. A consumer consumes 3 perfectly divisible goods \(x_1\), \(x_2\) and \(x_3\). The price of one unit of good 1 is 1 while the price of one unit of good 2 is 2 and the price of good 3 is \(3\). The utility function of the consumer is \(u(x_1,x_2)=x_1*x_2*x_3\) and his income is 12. Use julia to solve the consumers utility maximization problem, i.e. how many units of each good will the consumer consume? What is his utility level? (Hint: Solve the budget constraint for one of the variables and plug it into the objective. The resulting objective you still have to maximize over two variables.)

6. Week 7

variable name description
institutionenkennzeichen hospital id
Standortnr location id (only relevant for hospitals with several locations)
betten number of hospital beds
privat dummy: 1 if hospital is private and 0 else
freigemein dummy: 1 if hospital is a non-profit (usually owned by a religious organization)
births number of births
caesarean number of Caesarean sections
nCompBirths number of birth stations within a 50km radius
  (excluding the hospital itself and hospitals with the same "insitutionenkennzeichen")
nBirthsInRadius number of births within a 50km radius (as the crow flies)
demandPotMax approximate number of people living within a 50km radius
  1. Download the dataset "hospitalBirths.csv" on German hospitals. Open the dataset in Julia as a DataFrame using the CSV.jl and DataFrames.jl package. The meaning of some of the variables is given in the table above. Use the "describe" command to get some descriptive statistics. How many births are there on average in a hospital? How many Caesarean sections? Compute these variables only for those hospitals for which the number of births is not missing.
  2. Create a new variable "shareCsection" which contains the share of Caesarean sections in a hospital. Compute the mean of "shareC" by ownership status (i.e. separately for those hospitals that are private, non-profit, and public).
  3. Using only the hospitals with births, create a scatter plot with beds on the horizontal axis and births on the vertical axis. Can you color the dots by ownership status (i.e. private hospitals have different color than no-profits or public)? (Hint: use the StatsPlots.jl package.)
  4. Create a new variable "demandPerHospital" by dividing demandPotMax by nCompBirths. Plot demandPerHospital on the horizontal and shareC on the vertical axis in a scatter plot (maybe again coloring by ownership status) and check whether you can see a relationship between these variables or not. Also compute the correlation coefficient between these variables.

7. Week 8

  1. Generate 50 "random roles of a dice", i.e. use the "rand" command to – 50 times – select a random number in {1,2,3,4,5,6}. Next compute the frequency for each number (i.e. how many 1s, 2s etc. did we get in our 50 roles; hint: the FreqTables.jl package with its "freqtable" command is probably the quickest way of doing this). Use a ChiSquared test to test whether the dice is fair.
  2. You can extract the p-value from a test outcome using the "pvalue" command (e.g. if "test=chisqTest([20,30,40])" you get the p-value of the test testing that the frequency for all three outcomes is the same with "pvalue(test)"). Now write a function that (i) repeats the procedure from the previous exercise 100 times, (ii) each time saves the p-value and (iii) returns the number of times that the p-value was less than 0.05.
  3. Use the hospital dataset from last week. Concentrating on hospitals with births, test the hypothesis that the share of Caesarean sections in private hospitals is the same as the one in non-profit hospitals. Test the hypothesis that the share of Caesarean section is the same in Bavaria and in Thüringen (hint: the "land" variable equal to "BY" are Bavarian hospitals while "TH" are hospitals in Thüringen).
  4. Using the hospital dataset test whether larger hospitals are having a larger or smaller share of Caeserean sections by regressing "shareC" on "betten". Plot both the data and a regression line for this relationship. Repeat the regression but control for ownership status (i.e. use "privat" and "freigemein" as additional regressors).

8. Week 9

  1. Use the monopoly pricing problem from notebook 5 and use \(\alpha=2\) but now change the cost function to \(c(q)=\beta q^2\). Plot the monopoly price as a function of \(\beta\).
  2. Use the Cournot model from notebook 5 and determine the solution if the costs of firm \(i\) are not \(c_i*q_i\) but \(c_i*q_i^2\).
  3. Write a function npv(payments,delta) where payments is a vector of annual payments (i.e. the n/th element of /payments contains a payment in year n) and delta is a discount factor, i.e. a number between 0 and 1. The function npv returns the net present value of the payment stream discounted with the discount factor. For example, if \(npv([2.0,3.0,-4.0],0.9)=2.0+3.0*0.9-4.0*0.9^2\). Suppose an investor is considering to buy a house and then rent it out. The price of the house is 500.000 and the investor would charge a rent of 15000 per year. Furthermore, the investor expects to be able to resell the house after 20 years for a price of 250.000. Plot the net present value of this investment as a function of the discount factor \(\delta\).

Author: Christoph Schottmüller

Created: 2023-05-22 Mon 12:09