Regularized computation of cost and gradient