On Thu, 26 Jun 2014 19:38:45 +1000, Chris Angelico wrote: > On Thu, Jun 26, 2014 at 7:15 PM, Steven D'Aprano <st...@pearwood.info> > wrote: >> Here's an error that *cannot* occur with binary floats: the average of >> two numbers x and y is not guaranteed to lie between x and y! >> >> >> py> from decimal import * >> py> getcontext().prec = 3 >> py> x = Decimal('0.516') >> py> y = Decimal('0.518') >> py> (x + y) / 2 >> Decimal('0.515') >> >> >> Ouch! > > But what you're looking at is also a problem with intermediate rounding, > as the sum of .516 and .518 can't be represented in 3 digits.
Exactly. I picked 3 digits because it's much easier to write, and read, a 3 digit example than a 28 digit example. But the failure here is not a property of "too few digits", to be fixed by adding more significant digits. No matter how many digits you have, there are some calculations which cannot be performed exactly in that many digits. Although you seem to have missed the critical issue: this is a failure mode which *binary floats cannot exhibit*, but decimal floats can. The failure being that assert x <= (x+y)/2 <= y may fail if x and y are base 10 floats. I'm afraid my computational-mathematics skills are not good enough to prove this assertion, but Mark Dickinson on the Python-Dev mailing list made this claim, and I believe he knows what he is talking about. https://mail.python.org/pipermail/python-ideas/2014-March/026851.html If anyone can demonstrate such a failed assertion using floats, I'd love to see it. -- Steven -- https://mail.python.org/mailman/listinfo/python-list