Stephen Thorne <step...@thorne.id.au> wrote: > > def sign(x): > > if x==0.0: > > return 0.0 > > elif x>0.0: > > return 1.0 > > else: > > return -1.0 > > Isn't this approximately this? :: > > def sign(x): > return float(cmp(x, 0))
Yes cmp() is probably the closest function to sign. I'm new to python and here i discover at least 4 methods, i just make a small script for timing those methods (100 000 times each on a set of 10 values). I do not use timeit, i can't make it work easyly as it need a standalone env for each test. ---- the test script -------------------- #!/usr/bin/env python from math import atan2 import time def sign_0(x): if x==0.0: return 0.0 elif x>0.0: return 1.0 else: return -1.0 def sign_1(x): if x > 0 or (x == 0 and atan2(x, -1.) > 0.): return 1 else: return -1 def sign_2(x): return cmp(x, 0) sign_3 = lambda x:+(x > 0) or -(x < 0) def main(): candidates=[1.1,0.0,-0.0,-1.2,2.4,5.6,-8.2,74.1,-23.4,7945.481] startTime = time.clock() for i in range(100000): for value in candidates: s=sign_0(value) print "sign_0 : ",time.clock() - startTime startTime = time.clock() for i in range(100000): for value in candidates: s=sign_1(value) print "sign_1 : ",time.clock() - startTime startTime = time.clock() for i in range(100000): for value in candidates: s=sign_2(value) print "sign_2 : ",time.clock() - startTime startTime = time.clock() for i in range(100000): for value in candidates: s=sign_3(value) print "sign_3 : ",time.clock() - startTime if __name__ == '__main__' : main() ---- the results ----------------------------- My config : iMac (2,66 GHz intel dual core 2 duo) MacOS X 10.5.5 Python 2.5.1 sign_0 = 0.4156 second (0%) sign_1 = 0.5316 second (+28%) sign_2 = 0.6515 second (+57%) sign_3 = 0.5244 second (+26%) ---- conclusions ------------------------------- 1/ python is fast 2/ method (0) is the fastest 3/ cmp method (2) is the slowest 4/ the precise one (IEEE 754) is also fast (1) -- 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/> -- http://mail.python.org/mailman/listinfo/python-list