Can't exponentiate zero in NumPy
Todd Miller
jmiller at stsci.edu
Mon Sep 9 14:01:08 EDT 2002
Rick Muller wrote:
> I found out more about this problem, and I'm still hoping that someone
> can suggest a good fix.
>
> The problem comes when I take a power of a NumPy array that has very
> small values in it:
>
> >>> from Numeric import *
> >>> a = zeros(3,Float)
> >>> a**2
> array([0., 0., 0.])
> >>> a[1] = 1.e-310
> >>> a**2
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> OverflowError: math range error
>
> This crashes on Linux, but not on Mac OS X.
>
> Is this a bug or a feature?
>
> If it's a feature (which it might be), can someone offer a one-line
> workaround? What I would like to do is set everything below a small
> value (say 1.e-16) to zero. Obviously,
> >>> for i in range(len(a)): if a[i] < 1.e-16: a[i] = 0
> or something like it should work, but it will also be slow, and I was
> hoping that one of the Numeric UFuncs might do the same thing more
> effectively.
>
> Thanks in advance for any help anyone can offer.
>
> Rick
>
I think what you're looking for is "where". You use it like:
>>> b = where( abs(a) < 1.e-16, 0, a)
Which means "where the absolute value of a is less than 1.e-16, use 0,
else use a". The "<" operator only works like this for Python-2.1 and
up; prior to that you have to substitute a "lessthan" function call.
Todd
More information about the Python-list
mailing list