Formulating the cost function