1

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)  
Xiong89
  • 767
  • 2
  • 13
  • 24
  • 2
    Possible duplicate of [NumPy: Return 0 with divide by zero](http://stackoverflow.com/questions/26248654/numpy-return-0-with-divide-by-zero) – idjaw Feb 25 '16 at 02:08

3 Answers3

3

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)
third9
  • 464
  • 5
  • 10
1

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
Mark Skelton
  • 3,663
  • 4
  • 27
  • 47
1

How about this:

if (divisi == 0):
    print (0)
else:
    print(np.sum(single / divisi * binary, axis = -1))
Michael S
  • 726
  • 1
  • 10
  • 23