脾气暴躁,除以零:同一操作有两个不同的结果 [英] Numpy, divide by zero: two different results for the same operation

查看:83
本文介绍了脾气暴躁,除以零:同一操作有两个不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一番搜索后,我仍然在用numpy的零除法苦苦挣扎. 我立刻报告的矛盾让我震惊:

After having searched around a little bit, I'm still struggling with divisions by zero in numpy. I am stunned by the contradiction I report right away:

from numpy import *

seterr(all='ignore')    # Trying to avoid ZeroDivisionError, but unsuccessful.

def f(x) :
    return 1./(x-1.)

这样,当我执行f(1.)时,我得到 ZeroDivisionError: float division by zero.

With this, when I execute f(1.), I get ZeroDivisionError: float division by zero.

但是,当我定义 z = array( [ 1., 1. ] )并执行f(z),我没有收到任何错误,但是 array([ inf, inf]).

However, when I define z = array( [ 1., 1. ] ) and execute f(z), I do not get any error, but array([ inf, inf]).

如您所见,两个输出之间存在某种矛盾. 我的第一个问题是为什么.

As you can see, there is kind of a contradiction between both outputs. My first question is why.

理想情况下,我想获取inf作为f(1.)的输出,或者至少获取nan,但没有错误(因此是停止计算). 我的第二个问题是如何进行管理. 通过使用seterr注意我的失败尝试.

Ideally, I would like to get inf as the output of f(1.), or at least nan, but not an error (and therefore the stoppage of the calculation). My second question is how to manage this. Notice my failed attempt by making use of seterr.

推荐答案

Numpy不参与函数f.如果要更改输出,必须赶上ZeroDivisionError.

Numpy is not involved in your function f. You'll have to catch the ZeroDivisionError if you want to alter the output.

import numpy

def f(x) :
    try:
        return 1./(x-1.)
    except ZeroDivisionError:
        return numpy.nan

或使用numpy的除法:

Or use numpy's division:

import numpy

def f(x) :
    return numpy.divide(1., (x-1.))

或仅将numpy类型传递给f:

Or only pass numpy types to f:

import numpy

def f(x) :
    return 1./(x-1.)

x = numpy.float_(1)
print f(x) # prints inf

这篇关于脾气暴躁,除以零:同一操作有两个不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆