[Numpy-discussion] Catching and dealing with floating point errors

Warren Weckesser warren.weckesser@enthought....
Tue Nov 9 01:14:09 CST 2010


On Mon, Nov 8, 2010 at 3:20 PM, Warren Weckesser <
warren.weckesser@enthought.com> wrote:

>
>
> On Mon, Nov 8, 2010 at 2:52 PM, Skipper Seabold <jsseabold@gmail.com>wrote:
>
>> On Mon, Nov 8, 2010 at 3:45 PM, Warren Weckesser
>> <warren.weckesser@enthought.com> wrote:
>> >
>> >
>> > On Mon, Nov 8, 2010 at 2:17 PM, Skipper Seabold <jsseabold@gmail.com>
>> wrote:
>> >>
>> >> On Mon, Nov 8, 2010 at 3:14 PM, Skipper Seabold <jsseabold@gmail.com>
>> >> wrote:
>> >> > I am doing some optimizations on random samples.  In a small number
>> of
>> >> > cases, the objective is not well-defined for a given sample (it's not
>> >> > possible to tell beforehand and hopefully won't happen much in
>> >> > practice).  What is the most numpythonic way to handle this?  It
>> >> > doesn't look like I can use np.seterrcall in this case (without
>> >> > ignoring its actual intent).  Here's a toy example of the method I
>> >> > have come up with.
>> >> >
>> >> > import numpy as np
>> >> >
>> >> > def reset_seterr(d):
>> >> >    """
>> >> >    Helper function to reset FP error-handling to user's original
>> >> > settings
>> >> >    """
>> >> >    for action in [i+'='+"'"+d[i]+"'" for i in d]:
>> >> >        exec(action)
>> >> >    np.seterr(over=over, divide=divide, invalid=invalid, under=under)
>> >> >
>> >>
>> >> It just occurred to me that this is unsafe.  Better options for
>> >> resetting seterr?
>> >
>> >
>> > Hey Skipper,
>> >
>> > I don't understand why you need your helper function.  Why not just pass
>> the
>> > saved dictionary back to seterr()?  E.g.
>> >
>> > saved = np.seterr('raise')
>> > try:
>> >     # Do something dangerous...
>> >     result = whatever...
>> > except Exception:
>> >     # Handle the problems...
>> >     result = better result...
>> > np.seterr(**saved)
>> > return result
>> >
>>
>> Ha.  I knew I was forgetting something.  Thanks.
>>
>>
> Your question reminded me to file an enhancement request that I've been
> meaning to suggest for a while:
>     http://projects.scipy.org/numpy/ticket/1667
>
>

I just discovered that a context manager for the error settings already
exists: numpy.errstate.  So a nicer way to write that code is:

with np.errstate(all='raise'):
    try:
        # Do something dangerous...
        result = whatever...
    except Exception:
        # Handle the problems...
        result = better result...
return result


Warren
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20101109/0a1cef02/attachment-0001.html 


More information about the NumPy-Discussion mailing list