Numpy where and division by zero

后端 未结 5 1120
盖世英雄少女心
盖世英雄少女心 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:31

    If you wish to disable warnings in numpy while you divide by zero, then do something like:

    >>> existing = numpy.seterr(divide="ignore")
    >>> # now divide by zero in numpy raises no sort of exception
    >>> 1 / numpy.zeros( (2, 2) )
    array([[ inf,  inf],
           [ inf,  inf]])
    >>> numpy.seterr(*existing)
    

    Of course this only governs division by zero in an array. It will not prevent an error when doing a simple 1 / 0.

    In your particular case, if we wish to ensure that we work whether b is a scalar or a numpy type, do as follows:

    # ignore division by zero in numpy
    existing = numpy.seterr(divide="ignore")
    
    # upcast `1.0` to be a numpy type so that numpy division will always occur
    x = numpy.where(b == 0, a, numpy.float64(1.0) / b) 
    
    # restore old error settings for numpy
    numpy.seterr(*existing) 
    

提交回复
热议问题