1

Assume a simple 1-dimensional numpy array:

>>> x = np.array([1,3,5,0,3,2])

Now assume I want to perform the operation 1.0/x. I can do this with numpy:

>>> 1.0/x
array([ 1.        ,  0.33333333,  0.2       ,         inf,  0.33333333,
    0.5       ])

The problem here is the infinity (inf) result for the original element value 0, because 1.0/0 seems to return infinity in place of undefined behaviour.

Instead of infinity, I would like to provide my own custom value where these divide by 0 scenarios arise. While I know this can be accomplished using a loop, I would like to know whether there is any kind of idiomatic syntax for this kind of operation.

There's a related question here, but it only deals with the if something: (do this) else: (do nothing) scenario whereas my question is a if something: (do this) else: (do that) scenario.

2 Answers 2

4

You can always patch it up later:

a = 1.0/x
inf_ind = np.isinf(a)
a[inf_ind] = your_value

or

a[inf_ind] = f(x[inf_ind])

Which has the advantage of not getting in the way of the nice optimized numpy methods.

Sign up to request clarification or add additional context in comments.

Comments

3

Building on the previous answer, you can also set floating point callback modes to detect when you need to apply the inf transform.

I can't find a callback that gets called on each floating point error, however.

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

import numpy
class IsDivideError(object):
    def __init__(self):
        self.hasDivideError=False

    def callback(self, x,y):
        self.hasDivideError=True

ide=IsDivideError()
numpy.seterr(divide='call')
numpy.seterrcall(lambda x,y: ide.callback(x,y) )
x = numpy.array([1,3,5,0,3,2])
val=1.0/x
if(ide.hasDivideError):
    val[numpy.isinf(val)]=5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.