I am running in to RuntimeWarning: Invalid value encountered in divide
import numpy
a = numpy.random.rand((1000000, 100))
b = numpy.random.rand((1,100))
dots = numpy.dot(b,a.T)/numpy.dot(b,b)
norms = numpy.linalg.norm(a, axis =1)
angles = dots/norms ### Basically I am calculating angle between 2 vectors
There are some vectors in my a which have norm as 0. so while calculating angles it is giving runtime warning.
Is there a one line pythonic way to compute angles while taking into account norms which are 0?
angles =[i/j if j!=0 else -2 for i,j in zip(dots, norms)] # takes 10.6 seconds
But it takes a lot of time. Since all angles will have values between 1 and -1 and I need only 10 max values this will help me. This takes around 10.6 seconds which is insane.
解决方案
you can ignore warings with the np.errstate context manager and later replace nans with what you want:
import numpy as np
angle = np.arange(-5., 5.)
norm = np.arange(10.)
with np.errstate(divide='ignore'):
print np.where(norm != 0., angle / norm, -2)
# or:
with np.errstate(divide='ignore'):
res = angle/norm
res[np.isnan(res)] = -2