简体   繁体   中英

Python: How to enable division by zero and return zero value?

I have this following code that do help me reshape each lines in a file and perform simple division calculation. When divided by zero, this error occurred. Any helps are greatly appreciated.

print(np.sum(single / divisi * binary, axis = -1))
RuntimeWarning: divide by zero encountered in divide

print(np.sum(single / divisi * binary, axis = -1))
RuntimeWarning: invalid value encountered in multiply

Code

import numpy as np
from numpy import genfromtxt
import csv

binary = np.genfromtxt('binary.csv', delimiter = ',').reshape((-1, 101, 4))
single = np.genfromtxt('single.csv', delimiter = ',').reshape((-1, 4))
divisi = np.genfromtxt('divisi.csv', delimiter = ',').reshape((-1, 1, 4))

print(np.sum(single / divisi * binary, axis = -1))

The inclusion of this 4 lines or code still cannot solve it.

try:
    print(np.sum(single / divisi * binary, axis = -1))
except Exception:
    print(0)  

I recommend you to read this page. https://docs.python.org/2/tutorial/errors.html

As far as I know, when division by zero errors occur, It is recommended to use the code as below

try:
    print(np.sum(single / divisi * binary, axis = -1))
except ZeroDivisionError as e:
    print(0)

Just put your print in a try:except like this:

import numpy as np
from numpy import genfromtxt
import csv

binary = np.genfromtxt('binary.csv', delimiter = ',').reshape((-1, 101, 4))
single = np.genfromtxt('single.csv', delimiter = ',').reshape((-1, 4))
divisi = np.genfromtxt('divisi.csv', delimiter = ',').reshape((-1, 1, 4))

try:
    print(np.sum(single / divisi * binary, axis = -1))
except Exception:
    print(0)  #or print whatever you want when you divide by zero

How about this:

if (divisi == 0):
    print (0)
else:
    print(np.sum(single / divisi * binary, axis = -1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM