Numpy where and division by zero

后端 未结 5 1132
盖世英雄少女心
盖世英雄少女心 2020-12-04 01:00

I need to compute x in the following way (legacy code):

x = numpy.where(b == 0, a, 1/b) 

I suppose it worked in python-2.x (as

5条回答
  •  情书的邮戳
    2020-12-04 01:51

    numpy.where is not conditional execution; it is conditional selection. Python function parameters are always completely evaluated before a function call, so there is no way for a function to conditionally or partially evaluate its parameters.

    Your code:

    x = numpy.where(b == 0, a, 1/b)
    

    tells Python to invert every element of b and then select elements from a or 1/b based on elements of b == 0. Python never even reaches the point of selecting elements, because computing 1/b fails.

    You can avoid this problem by only inverting the nonzero parts of b. Assuming a and b have the same shape, it could look like this:

    x = numpy.empty_like(b)
    mask = (b == 0)
    x[mask] = a[mask]
    x[~mask] = 1/b[~mask]
    

提交回复
热议问题