fix code for numerical stability