[Python-Dev] Caching float(0.0)

Scott David Daniels Scott.Daniels at Acm.Org
Tue Oct 3 19:45:50 CEST 2006


James Y Knight wrote:
> On Oct 3, 2006, at 8:30 AM, Martin v. Löwis wrote:
>> As Michael Hudson observed, this is difficult to implement, though:
>> You can't distinguish between -0.0 and +0.0 easily, yet you should.
> 
> Of course you can. It's absolutely trivial. The only part that's even  
> *the least bit* sketchy in this is assuming that a double is 64 bits.  
> Practically speaking, that is true on all architectures I know of,  
> and if it's not guaranteed, it could easily be a 'configure' time check.
> 
> typedef union {
>      double d;
>      uint64_t i;
> } rawdouble;
> 
> int isposzero(double a) {
>      rawdouble zero;
>      zero.d = 0.0;
>      rawdouble aa;
>      aa.d = a;
>      return aa.i == zero.i;
> }
> 
> int main() {
>      if (sizeof(double) != sizeof(uint64_t))
>          return 1;
> 
>      printf("%d\n", isposzero(0.0));
>      printf("%d\n", isposzero(-0.0));
> 
> }
> 

And you should be able to cache the single positive zero
with something vaguely like:
     PyObject *
     PyFloat_FromDouble(double fval)
     {       ...
             if (fval == 0.0 && raw_match(&fval, cached)) {
                 PY_INCREF(cached);
                 return cached;
             }
             ...

-- 
-- Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-Dev mailing list