On Fri, 04 Apr 2014 02:13:13 -0600, Ian Kelly wrote: > On Fri, Apr 4, 2014 at 1:52 AM, Steven D'Aprano > <steve+comp.lang.pyt...@pearwood.info> wrote: >> py> from decimal import * >> py> getcontext().prec = 16 >> py> x = Decimal("0.7777777777787516") py> y = >> Decimal("0.7777777777787518") py> (x + y) / 2 >> Decimal('0.7777777777787515') >> >> "Guido, why can't Python do maths???" > > Well, you need to work within the system: > >>>> (5*x + 5*y) / 10 > Decimal('0.7777777777787517') > > Actually, I have no idea whether that formula can be relied upon or the > correctness of the above was just luck.
And what happens when x+y would have been calculated correctly, but one, or both, of 5*x or 5*y loses catastrophically loses accuracy due to overflow? py> x = 3.1e307 py> y = 3.3e307 py> (x+y)/2 3.2e+307 py> (5*x+5*y)/10 inf (I've used regular floats here out of laziness, the same principle applies to Decimals -- there will be *some* number x which is finite, but 5*x overflows to infinity.) -- Steven D'Aprano http://import-that.dreamwidth.org/ -- https://mail.python.org/mailman/listinfo/python-list