Implemented gradient calculation logic