no sign() function ?

Pierre-Alain Dorange pdorange at pas-de-pub-merci.mac.com
Mon Dec 22 12:31:44 CET 2008


Christian Heimes <lists at cheimes.de> wrote:

> 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'm using 2.5.2 at that time, but copysign() is fine.

with :
        s=copysign(1.0,x)
it return the sign (-1.0, 0.0, +1.0)

 
> > 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? :)

I was...

> 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

Thanks
As my need is for a game and that i do not have IEEE real concern, i
would simply using my simple function (but not as accurate) :

def sign(x):
    if x==0.0:
        return 0.0
    elif x>0.0:
        return 1.0
    else:
        return -1.0

-- 
Pierre-Alain Dorange        <http://microwar.sourceforge.net/>

Ce message est sous licence Creative Commons "by-nc-sa-2.0"
        <http://creativecommons.org/licenses/by-nc-sa/2.0/fr/>



More information about the Python-list mailing list