Py-ser
Py-ser

Reputation: 2098

Return zero value if division by zero encountered

I have two lists a and b of equal length. I want to calculate the sum of their ratio:

c = np.sum(a/b)

how can I have a zero (0) value in the summation coefficient when there is division by zero?

EDIT: Here a couple of answers I tested for my case, and still raise the error. Probably I am missing something. The aray that contains zero elements is counts:

try:
    cnterr = (counts/np.mean(counts))*(((cnterr/counts)**2 + (meanerr/np.mean(counts))**2 ))**1/2
except ZeroDivisionError:
    cnterr = (counts/np.mean(counts))*(((meanerr/np.mean(counts))**2 ))**1/2

RuntimeWarning: divide by zero encountered in divide
cnterr = (counts/np.mean(counts))*(((cnterr/counts)**2 + (meanerr/np.mean(counts))**2 ))**1/2

And also by np.where():

cnterr = np.where(counts != 0, ((counts/np.mean(counts))*(((cnterr/counts)**2 + (meanerr/np.mean(counts))**2 ))**1/2), 0)

Raise the same error.

Upvotes: 2

Views: 1755

Answers (5)

John B
John B

Reputation: 3646

This should work.

c = []
for i, j in enumerate(a):
    if b[i] != 0:
        c += [j/b[i]]
    else:
        c += [0]

c = sum(c)

Upvotes: 0

emesday
emesday

Reputation: 6186

To sum values except divide by 0,

sel = b != 0
c = np.sum(a[sel]/b[sel])

The arrays are float, you may need to use

sel = np.bitwise_not(np.isclose(b, 0))

UPDATE

If a and b are not np.array, write the follow code in the first.

a = np.array(a)
b = np.array(b)

Upvotes: 3

YXD
YXD

Reputation: 32511

c = np.where(b != 0, a/b, 0).sum()

See: http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

Upvotes: 2

Lee
Lee

Reputation: 31040

This works, it puts a 0 in the list where there is a divide by zero:

c = np.sum([x/y if y else 0 for x,y in zip(a,b)])

Or, a variation on @mskimm's answer. Note, you first need to convert your input lists to numpy arrays:

a=np.array(a)
b=np.array(b)
c=np.sum(a[b!=0]/b[b!=0])

Upvotes: 0

ssm
ssm

Reputation: 5373

This is also simple:

c = 0 if 0 in b else sum(a/b)

Upvotes: -1

Related Questions