Funtion to compute cost, gradient