Re:Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)? ...
by Scaevolus on Thursday March 27, 2014 @02:17PM
(#7482198)
Note that recent Python versions use Gay's correctly-rounded conversions, so .1+(.2+.3) displays as .6, since that's equivalent when converted back to binary floating point. http://bugs.python.org/issue1580
Re:Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)? ...
by whoopdedo on Thursday March 27, 2014 @09:17PM
(#7484677)
If you want an exact representation, C99 has the %a format specifier for base-16 floating point. It seems that Python 3 doesn't support it but Lua 5.2 does.
Lua 5.2.2 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> print(string.format(" 0.1 (%a)\n+ 0.2 (%a)\n= %a\n+ 0.3 (%a)\n= %a", 0.1,0.2,0.1+0.2, 0.3, 0.1+0.2+0.3))
0.1 (0x1.999999999999ap-4)
+ 0.2 (0x1.999999999999ap-3)
= 0x1.3333333333334p-2
+ 0.3 (0x1.3333333333333p-2)
= 0x1.3333333333334p-1
> print(string.format(" 0.2 (%a)\n+ 0.3 (%a)\n= %a\n+ 0.1 (%a)\n= %a", 0.2,0.3,0.2+0.3, 0.1, 0.2+0.3+0.1))
0.2 (0x1.999999999999ap-3)
+ 0.3 (0x1.3333333333333p-2)
= 0x1p-1
+ 0.1 (0x1.999999999999ap-4)
= 0x1.3333333333333p-1
Re:Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)? ...
by enupten on Friday March 28, 2014 @03:04AM
(#7485738)
I don't know if you realise that by converting a double "0.1" into the python decimal of a much larger size, you're
bound to get garbage.
Edit: I see what you're doing now. I didn't appreciate enough how converting to decimals had such unpleasant effects :) Thanks.
Re:Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)? ...
by haberman on Friday March 28, 2014 @04:08AM
(#7485897)
I'm not sure what you're trying to say. 0.1000000000000000055511151231257827021181583404541015625 is the precise value of float(0.1). It is not "garbage" or an approximation in any way. It is exact.
Here's 0.1 + 0.2 + 0.3:
The operands can't be represented exactly as floating point so they are rounded to the nearest floating-point number before the addition even happens. And once the addition does happen, it is rounded to the nearest representable floating point value.Now we can look at the same for 0.1 + (0.2 + 0.3):
It's interesting to note that the first addition ends up being exact! This is a bit lucky, because 0.5 is exactly representable in floating point and the initial operands got rounded in opposite directions. It's also interesting that 0.6... only turns into 0.599999... at the point that we round the answer.You can play around with this stuff conveniently using the Python "Decimal" module.
You can also use my tool "dumpfp" (https://github.com/haberman/dumpfp) to inspect the value of a floating-point number in detail: