[Python-Dev] Caching float(0.0)

Alastair Houghton alastair at alastairs-place.net
Wed Oct 4 01:40:26 CEST 2006

On 3 Oct 2006, at 17:47, 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,

How about doing 1.0 / x, where x is the number you want to test?  On  
systems with sane semantics, it should result in an infinity, the  
sign of which should depend on the sign of the zero.  While I'm sure  
there are any number of places where it will break, on those  
platforms it seems to me that you're unlikely to care about the  
difference between +0.0 and -0.0 anyway, since it's hard to otherwise  
distinguish them.


   double value_to_test;


   if (value_to_test == 0.0) {
     double my_inf = 1.0 / value_to_test;

     if (my_inf < 0.0) {
       /* We have a -ve zero */
     } else if (my_inf > 0.0) {
       /* We have a +ve zero */
     } else {
       /* This platform might not support infinities (though we might  
get a
          signal or something rather than getting here in that  
case...) */

(I should add that presently I've only tried it on a PowerPC, because  
it's late and that's what's in front of me.  It seems to work OK here.)

Kind regards,



More information about the Python-Dev mailing list