replace variance calculation with numerically stable version