compute the costfunction