Make division by zero equal to zero
I think try
except
(as in Cyber's answer) is usually the best way (and more pythonic: better to ask forgiveness than to ask permission!), but here's another:
def safe_div(x,y): if y == 0: return 0 return x / y
One argument in favor of doing it this way, though, is if you expect ZeroDivisionError
s to happen often, checking for 0 denominator ahead of time will be a lot faster (this is python 3):
import timedef timing(func): def wrap(f): time1 = time.time() ret = func(f) time2 = time.time() print('%s function took %0.3f ms' % (f.__name__, int((time2-time1)*1000.0))) return ret return wrapdef safe_div(x,y): if y==0: return 0 return x/ydef try_div(x,y): try: return x/y except ZeroDivisionError: return 0@timingdef test_many_errors(f): print("Results for lots of caught errors:") for i in range(1000000): f(i,0)@timingdef test_few_errors(f): print("Results for no caught errors:") for i in range(1000000): f(i,1)test_many_errors(safe_div)test_many_errors(try_div)test_few_errors(safe_div)test_few_errors(try_div)
Output:
Results for lots of caught errors:safe_div function took 185.000 msResults for lots of caught errors:try_div function took 727.000 msResults for no caught errors:safe_div function took 223.000 msResults for no caught errors:try_div function took 205.000 ms
So using try
except
turns out to be 3 to 4 times slower for lots of (or really, all) errors; that is: it is 3 to 4 times slower for iterations that an error is caught. The version using the if
statement turns out to be slightly slower (10% or so) when there are few (or really, no) errors.