Added NaN check at the final stage of the calculations