modified to handle NaN