[Numpy-discussion] log of negative real numbers -> RuntimeWarning: invalid value encountered in log

Eric Wieser wieser.eric+numpy at gmail.com
Mon May 25 09:47:45 EDT 2020


One explanation for this behavior is that doing otherwise would be slow.

Consider an array like

arr = np.array([1]*10**6 + [-1])
ret = np.log(arr)

Today, what happens is:

   - The output array is allocated as np.double
   - The input array is iterated over, and log evaluated on each element in
   turn

For what you describe to happen, the behavior would have to be either:

   - The output array is allocated as np.double
   -

   The input array is iterated over, and log evaluated on each element in
   turn
   -

   If any negative element is encountered, allocate a new array as
   np.cdouble, copy all the data over, then continue. This results in the
   whole array being promoted.

or:

   - The input array is iterated over, and checked to see if all the values
   are positive
   -

   The output array is allocated as np.double or np.cdouble based on this
   result
   -

   The input array is iterated over, and log evaluated on each element in
   turn

In either case, you’ve converted a 1-pass iteration to a 2-pass one.

There are static-typing-based explanations for this behavior too, but I’ll
let someone else present one of those.

Eric

On Mon, 25 May 2020 at 14:33, Brian Racey <raceybe at gmail.com> wrote:

> Why does numpy produce a runtime warning (invalid value encountered in
> log) when taking the log of a negative number? I noticed that if you coerce
> the argument to complex by adding 0j to the negative number, the expected
> result is produced (i.e. ln(-1) = pi*i).
>
> I was surprised I couldn't find a discussion on this, as I would have
> expected others to have come across this before. Packages like Matlab
> handle negative numbers automatically by doing the complex conversion.
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at python.org
> https://mail.python.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20200525/6b27ce54/attachment.html>


More information about the NumPy-Discussion mailing list