modified algorithm for better numerical stability