calculates the cost function