如何用除以零返回 0 [英] How to return 0 with divide by zero

查看:27
本文介绍了如何用除以零返回 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中执行元素智能除法,但如果遇到零,我需要商为零.

例如:

array1 = np.array([0, 1, 2])array2 = np.array([0, 1, 1])array1/array2 # 应该是 np.array([0, 1, 2])

我总是可以在我的数据中使用 for 循环,但要真正利用 numpy 的优化,我需要除以零错误时除法函数返回 0,而不是忽略错误.

除非我遗漏了一些东西,否则它似乎没有 numpy.seterr() 可以在出错时返回值.有没有人对如何在设置自己的除以零错误处理时充分利用 numpy 有任何其他建议?

解决方案

在 numpy v1.7+ 中,您可以利用 ufuncs.您可以在一行中完成操作,而不必处理 errstate 上下文管理器.

<预><代码>>>>a = np.array([-1, 0, 1, 2, 3], dtype=float)>>>b = np.array([ 0, 0, 0, 2, 2], dtype=float)# 如果你不传递 `out`,那么 (b == 0) 的索引将不会被初始化!>>>c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)>>>打印(c)[ 0. 0. 0. 1. 1.5]

在这种情况下,它会在 b 不等于零的任何地方进行除法计算.当 b 等于 0 时,它与您最初在 'out' 参数中给它的任何值保持不变.

I'm trying to perform an element wise divide in python, but if a zero is encountered, I need the quotient to just be zero.

For example:

array1 = np.array([0, 1, 2])
array2 = np.array([0, 1, 1])

array1 / array2 # should be np.array([0, 1, 2])

I could always just use a for-loop through my data, but to really utilize numpy's optimizations, I need the divide function to return 0 upon divide by zero errors instead of ignoring the error.

Unless I'm missing something, it doesn't seem numpy.seterr() can return values upon errors. Does anyone have any other suggestions on how I could get the best out of numpy while setting my own divide by zero error handling?

解决方案

In numpy v1.7+, you can take advantage of the "where" option for ufuncs. You can do things in one line and you don't have to deal with the errstate context manager.

>>> a = np.array([-1, 0, 1, 2, 3], dtype=float)
>>> b = np.array([ 0, 0, 0, 2, 2], dtype=float)

# If you don't pass `out` the indices where (b == 0) will be uninitialized!
>>> c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
>>> print(c)
[ 0.   0.   0.   1.   1.5]

In this case, it does the divide calculation anywhere 'where' b does not equal zero. When b does equal zero, then it remains unchanged from whatever value you originally gave it in the 'out' argument.

这篇关于如何用除以零返回 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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