finished gradient and cost functions