Fix gradient function and add test
Merge pull request #5321 from JuliaLang/anj/fixgrad

Fix gradient function and add test