Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The variance of a list of reals [a_1, a_2, ..., a_n] is the average of the squar

ID: 3782191 • Letter: T

Question

The variance of a list of reals [a_1, a_2, ..., a_n] is the average of the squares minus the square of the average. i.e., sigma_i = 1^n a_1^2/n - (sigma_i = 1^n a_1/n)^2 Write the most elegant ML function variance you can that computes the variance. (Short and clear is ideal). The function takes as input a list of integers. Remember that ML types all the expressions it encounters and does not mix integers and reals. If you have an integer that you wish to convert to a real for arithmetic purposes you can use the function fn real: int rightarrow real. Similarly, do recall that the types of the two literals 0 and 0.0 are 0: int while 0.0: real.

Explanation / Answer

program varianceProg
   version 11
   args todo variance lnf

   tempvar xb res1 res2
   mleval `xb' = `variance', eq(1)
   mleval `res1' = `variance', eq(2)
   mleval `res2' = `variance', eq(3)

   tempvar res3 epsilon lambda
   quietly gen double `res3' = exp(`res1') + exp(`res2')
   quietly gen double `epsilon' = $ML_y1 - `xb'
   quietly gen double `lambda' = sqrt( exp(`res2')/exp(`res1') )

   mlsum `lnf' = (1/2) * ln(2/_pi) - ln(sqrt(`res3')) /*
*/ + ln(normal(-(`epsilon'*`lambda') / sqrt(`res3'))) - `epsilon'^2 / (2*`res3')
end