Cost function for both single and multi variable cases