cjm2671
cjm2671

Reputation: 19466

Best way to handle ZeroDivisonError?

I've got the following code:

def chunk_trades(A):
    last = A[0]
    new = []
    for x in A.iteritems():
        if np.abs((x[1]-last)/last) > 0.1:
            new.append(x[1])
            last = x[1]
        else:
            new.append(last)
    s = pd.Series(new, index=A.index)
    return s

Sometimes last can be zero. In this case, I'd like it to just carry on gracefully as if last was almost zero.

What's the cleanest way?

Upvotes: 2

Views: 107

Answers (3)

YOBA
YOBA

Reputation: 2807

Just Replace your line by this:

if not last or np.abs((x[1]-last)/last) > 0.1:

This will not raise an exception since the left assertion is checked first.

Upvotes: 1

Mikhail T.
Mikhail T.

Reputation: 1330

If I anderstand correctly, when last == 0 youl'll get ZeroDivisionError, won't you? If yes, please consider following slightly modified version of your code:

def chunk_trades(A):
    last = A[0]
    new = []
    for x in A.iteritems():
        try:
            if np.abs((x[1]-last)/last) > 0.1:
                new.append(x[1])
                last = x[1]
            else:
                new.append(last)
        except ZeroDivisionError:
            eps = 1e-18 # arbitary infinitesmall number
            last = last + eps
            if np.abs((x[1]-last)/last) > 0.1:
                new.append(x[1])
                last = x[1]
            else:
                new.append(last)

    s = pd.Series(new, index=A.index)
    return s

Upvotes: 0

advance512
advance512

Reputation: 1358

Not sure if you would really want to divide by "almost 0", since the result will be "almost infinity", but you can also do this:

if last == 0:
   last = sys.float_info.min

This is the minimum positive normalized float, i.e. the value closest to zero.

Source: https://docs.python.org/2/library/sys.html#sys.float_info

Upvotes: 1

Related Questions