Handling division by zero

Terry Reedy tjreedy at home.com
Mon Dec 3 22:12:48 EST 2001


"Stephen Boulet" <stephen.boulet at motorola.com> wrote in message
news:3C0C15AF.E1441FBF at motorola.com...
> I have some math operations going on where sometimes the divisor
will be
> zero.
>
> Is this an acceptable way to handle this:
>   1. test if the divisor is zero
>   2. if so, instead of dividing by it, multiply by a large number
> ?

1. is okay, but see below.  2. depends on application.

Alternative.

try:
  z= x/y
except ZeroDivisionError: #or whatever its called
  z=x*big

If y = 0 is rare (say < 10% of cases), this is on average faster

Terry J. Reedy






More information about the Python-list mailing list