changed code so that residual is only added if sum != 0.0