[Numpy-discussion] numpy.log does not raise exceptions

Robert Kern robert.kern@gmail....
Sat Aug 27 15:37:14 CDT 2011


On Sat, Aug 27, 2011 at 15:09, Dominique Orban
<dominique.orban@gmail.com> wrote:
> Hi,
>
> I'm wondering why numpy.log doesn't raise a ValueError exception the
> way math.log does:
>
> 1< import numpy as np
> 2< np.log([-1])
> Warning: invalid value encountered in log
> 2> array([ nan])
>
> 3< import math
> 4< math.log(-1)
> ---------------------------------------------------------------------------
> ValueError                                Traceback (most recent call last)
>
> It would make it a lot easier to trap domain errors than using isnan().

The reason we don't raise exceptions by default is because when
processing large arrays, you usually don't want to cancel the whole
operation just because some values were out of the domain. You would
rather get an array with NaNs in the elements that had invalid inputs
so you can do something useful with the other elements and actually
track down where the NaNs got their bad inputs. Always raising an
exception destroys that information.

That said, if you do want to raise an exception, this is entirely configurable.

  http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html

[~]
|1> import numpy as np

[~]
|2> np.log([-1])
Warning: invalid value encountered in log
array([ nan])

[~]
|3> np.seterr(invalid='raise')
{'divide': 'print', 'invalid': 'print', 'over': 'print', 'under': 'ignore'}

[~]
|4> np.log([-1])
---------------------------------------------------------------------------
FloatingPointError                        Traceback (most recent call last)
/Users/rkern/<ipython-input-4-6f7031b9c723> in <module>()
----> 1 np.log([-1])

FloatingPointError: invalid value encountered in log


-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco


More information about the NumPy-Discussion mailing list