Refactor the gradient calculation