refactored add_derivative function