Working version with numerical derivatives