numpy.where behavior

Tim Hochberg tim.hochberg at ieee.org
Mon Nov 13 21:10:09 CST 2006


vallis.35530053 at bloglines.com wrote:
> Using numpy 1.0, why does
>
>
>
>   
>>>> a = numpy.array([0.0,1.0,2.0],'d')
>>>>         
>
>   
>>>> numpy.where(a
>>>>         
> == 0.0,1,1/a)
>
>
>
> give the correct result, but with the warning "Warning: divide
> by zero encountered in divide"?
>
>
>
> ? I thought that the point of where was
> that the second expression is never used for the elements where the condition
> evaluates true. 
>
>
>
> If this is the desired behavior, is there a way to suppress
> the warning?
>   
Robert Kern has already pointed you to seterr. If you are using Python 
2.5, you also have the option using the with statement, which is more 
convenient if you want to temporarily change the error state. You'll 
need a "from __future__ import with_statement" at the top of your file. 
Then you can temporarily disable errors as shown:

     >>> a = zeros([3])
     >>> b = 1/a  # This will warn
    Warning: divide by zero encountered in divide
     >>> with errstate(divide='ignore'): # But this will not
    ...     c = 1/a
    ...
     >>> d = 1/a # And this will warn again since the error state is
    restored when we exit the block
    Warning: divide by zero encountered in divide


Another little tidbit: this is not as general as where, and could 
probably be considered a little too clever to be clear, but:

        b = 1 / (a + (a==0.0))

is faster than using where in this particular case and sidesteps the 
divide by zero issue altogether.

-tim



-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642




More information about the Numpy-discussion mailing list