[Python-Dev] Caching float(0.0)

Tim Peters tim.peters at gmail.com
Wed Oct 4 07:29:58 CEST 2006


[Tim]
>> Someone (Fred, I think) introduced a front-end optimization to
>> collapse that to plain LOAD_CONST, doing the negation at compile time.

> I did the original change to make negative integers use just LOAD_CONST, but I
> don't think I changed what was generated for float literals.  That could be
> my memory going bad, though.

It is ;-)  Here under Python 2.2.3:

>>> from dis import dis
>>> def f(): return 0.0 + -0.0 + 1.0 + -1.0
...
>>> dis(f)
          0 SET_LINENO               1

          3 SET_LINENO               1
          6 LOAD_CONST               1 (0.0)
          9 LOAD_CONST               1 (0.0)
         12 UNARY_NEGATIVE
         13 BINARY_ADD
         14 LOAD_CONST               2 (1.0)
         17 BINARY_ADD
         18 LOAD_CONST               3 (-1.0)
         21 BINARY_ADD
         22 RETURN_VALUE
         23 LOAD_CONST               0 (None)
         26 RETURN_VALUE

Note there that "0.0", "1.0", and "-1.0" were all treated as literals,
but that "-0.0" still triggered a UNARY_NEGATIVE opcode.  That was
after "the fix".

You don't remember this as well as I do since I probably had to fix
it, /and/ I ate enormous quantities of chopped, pressed, smoked,
preservative-laden bag o' ham at the time.  You really need to do both
to remember floating-point trivia.  Indeed, since I gave up my bag o'
ham habit, I hardly ever jump into threads about fp trivia anymore.
Mostly it's because I'm too weak from not eating anything, though --
how about lunch tomorrow?

> The code changed several times as people with more numeric-fu that myself
> fixed all sorts of border cases.  I've tried really hard to stay away from
> the code generator since then.  :-)

Successfully, too!  It's admirable.


More information about the Python-Dev mailing list