no sign() function ?

Christian Heimes lists at cheimes.de
Mon Dec 22 06:18:27 EST 2008


Pierre-Alain Dorange schrieb:
> I don't find any sign(x) function in the math library (return the sign
> of the value).
> I've read that math module is a wrapper to C math lib and that C math
> lib has not sign(), so...

Starting with Python 2.6 the math and cmath modules have a copysign
function.

> I've implement my own sign function of course (it's easy) but a standard
> one in math would be better and could be faster.

Sure? :) Are you aware that the IEEE 754 standard makes a difference
between the floats +0.0 and -0.0?

from math import atan2
def sign(x):
    if x > 0 or (x == 0 and atan2(x, -1.) > 0.):
        return 1
    else:
        return -1




More information about the Python-list mailing list