Fixed calculation of cost function.