debugged gradient computation (did not properly check for infinite values)