Strange result with math.atan2()

Ben Caradoc-Davies ben at wintersun.org
Tue May 2 09:31:09 EDT 2006


Vedran Furač wrote:
> I think that this results must be the same:
> In [3]: math.atan2(-0.0,-1)
> Out[3]: -3.1415926535897931
> In [4]: math.atan2(-0,-1)
> Out[4]: 3.1415926535897931

-0 is converted to 0, then to 0.0 for calculation, losing the sign. You 
might as well write 0.0 instead of -0

The behaviour of atan2 conforms to the ISO C99 standard (Python is 
implemented in C). Changing the sign of the first argument changes the 
sign of the output, with no special treatment for zero.

> In [5]: -0 == -0.0
> Out[5]: True

The constant -0 is an integer and is immediately converted to 0 (an 
integer). Two's-complement integers have no separate sign bit, and only 
one representation for zero. The integer -0 is identical in all respects 
to the integer 0

The constant -0.0 is a float, stored as an IEEE 754 bit pattern, and has 
a bit used to represent sign. The constants 0.0 and -0.0 compare equal, 
and both compare equal to 0, yet 0.0 and -0.0 have distinct bit patterns.

Because Python uses the C implementation of atan2, both arguments are 
converted to floats before calculation. -0 is converted to 0, then to 0.0

The behaviour of atan2 is mandated by ISO C99 (ISO/IEC 9899:1999). See 
the manuals of some implementers who tabulate these special values:

http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atan2.3.html
http://www.ugcs.caltech.edu/manuals/libs/mpfr-2.2.0/mpfr_22.html

-- 
Ben Caradoc-Davies <ben at wintersun.org>
http://wintersun.org/
"Those who deny freedom to others deserve it not for themselves."
- Abraham Lincoln



More information about the Python-list mailing list