Turn off ZeroDivisionError?

Ryszard Szopa ryszard.szopa at gmail.com
Sat Feb 9 18:10:21 EST 2008


On Feb 9, 11:03 pm, Neal Becker <ndbeck... at gmail.com> wrote:
> I'd like to turn off ZeroDivisionError.  I'd like 0./0. to just give NaN,
> and when output, just print 'NaN'.  I notice fpconst has the required
> constants.  I don't want to significantly slow floating point math, so I
> don't want to just trap the exception.

What you are trying to do looks like something very, very wrong, in
the vast majority of cases. Think: normal Python code and the
interpreter itself are written under the assumption that dividing by
zero doesn't pass silently. Changing it is asking for bogus behavior.

Have you actually timed how big is the overhead of catching the
exception?

In [83]: import timeit

In [84]: x = """\
try:
    1.0/rand.next()
except:
    pass"""

In [85]: t = timeit.Timer(x, 'import random \nrand =
iter([random.randint(0,10) for i in xrange(1000000)])')

In [86]: x_nozero = "1.0/rand.next()"

In [87]: t_nozero = timeit.Timer(x_nozero, 'import random \nrand =
iter([random.randint(1,10) for i in xrange(1000000)])')

In [88]: t.repeat()
Out[88]: [0.91399192810058594, 0.8678128719329834,
0.86738419532775879]

In [89]: t_nozero.repeat()
Out[89]: [0.64040493965148926, 0.58412599563598633,
0.59886980056762695]

As you can see, the overhead isn't so huge.

If this overhead is too big for you, you should consider using a
different language (C? Fortran?) or at least a numeric package for
Python (NumPy?).

Anyway, turning off division by zero signaling looks like the wrong
answer to the wrong question.

HTH,

    -- Richard



More information about the Python-list mailing list