numerically stable algo