Made computation numerically stable; modified code balance