Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Apr 4 03:52:46 EDT 2014
On Fri, 04 Apr 2014 09:43:15 +1100, Chris Angelico wrote:
> While I am interested in seeing a Decimal literal syntax in Python, and
> I would support a shift to have "1.2" evaluate as a Decimal (but not
> soon - it'd break backward compat *hugely*)
I used to think the same thing, but have since learned that it's not a
coincidence or accident that people seriously interested in numerical
computation nearly always stick to binary floats. I think it's a little
harsh to say that only dilettantes and amateurs use base-10 floats, but
only a little. Base-10 has one, and only one, thing going for it: the
number you type (in decimal) is the number you get (within the limits of
precision). Apart from that, in every way IEEE-754 binary floats are as
good or better than any other choice of base, including decimal. The same
floating-point complications that plague binary floats also plague
decimal ones, only worse.
I really should stop being shocked by anything I learn about floating
point numbers, but something that knocked my socks off when I learned it
was that as simple an operation as taking the average of two floats is
problematic in decimal. In base-2, and given round-to-nearest division,
(x+y)/2 is always within the range x...y. But that's not necessarily the
case in base-10 floats: sometimes the average of two numbers is not
between those two numbers. Contrast binary floats:
py> x = 0.7777777777787516
py> y = 0.7777777777787518
py> (x + y) / 2
0.7777777777787517
with decimal:
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???"
(Oh lordy, can you imagine Ranting Rick getting onto that???)
I've changed my mind about Python using Decimal as the default numeric
type. I think that would send a very strong message that Python is not
for serious numeric work.
--
Steven D'Aprano
http://import-that.dreamwidth.org/
More information about the Python-list
mailing list