为什么NumPy浮动不能给ZeroDivisionError? [英] Why don't NumPy floats give ZeroDivisionError?
问题描述
我注意到在代码中:
import numpy as np
pre>
a = 0.0
打印a / a
b = np.array([0.0])
print b [0] / b [0]
第一个打印函数抛出一个ZeroDivisionError,但第二个输出
nan
。我知道type(b [0])
是numpy.float64
,而类型(a)
是float
。我有两个问题:
1)为什么这样实现?
2)有没有它会抛出一个ZeroDivisionError?
解决方案我必须说,我更惊讶的是,普通的Python浮点数会引发错误。据我所知,由于IEEE 754中定义了浮点数方式,所以返回
NaN
是正确的方式。
http://grouper.ieee.org/groups/754/faq.html #exceptions
为什么不分零(或溢出或下溢)停止程序或触发一个错误?为什么数字标准包括不是数字(
NaN
)?
754模式鼓励强大的程序。它不仅适用于数值分析人员,还适用于电子表格用户,数据库系统甚至咖啡壶。
NaN
和无限的传播规则允许无关紧要的例外消失。类似地,渐进的下溢在精度范围内维持错误属性。
当异常情况需要注意时,可以通过陷阱或通过状态标志在方便的时间立即检查它们。陷阱可用于停止程序,但不可恢复的情况非常罕见。简单地停止程序不是嵌入式系统或网络代理的选择。更常见的是,陷阱记录诊断信息或替代有效结果。
标志提供可预测的控制流程和速度。他们的使用需要程序员知道特殊的条件,但标志粘性允许程序员延迟处理特殊条件,直到必要。
错误是在处理没有这种能力的数字(如积分分割)时的适当回应。
I noticed that in the code:
import numpy as np a = 0.0 print a / a b = np.array( [0.0] ) print b[0] / b[0]
the first print function throws a ZeroDivisionError, but the second one outputs
nan
. I'm aware thattype(b[0])
isnumpy.float64
, whiletype(a)
isfloat
. I have two questions:1) Why was it implemented this way?
2) Is there anyway to have it throw a ZeroDivisionError?
解决方案I must say, I am more surprised that the regular Python floats do throw an error. As far as I can understand, returning
NaN
is the correct way, given the way floats are defined in IEEE 754.http://grouper.ieee.org/groups/754/faq.html#exceptions
Why doesn't division by zero (or overflow, or underflow) stop the program or trigger an error? Why does a standard on numbers include "not-a-number" (
NaN
)?The 754 model encourages robust programs. It is intended not only for numerical analysts but also for spreadsheet users, database systems, or even coffee pots. The propagation rules for
NaN
s and infinities allow inconsequential exceptions to vanish. Similarly, gradual underflow maintains error properties over a precision's range.When exceptional situations need attention, they can be examined immediately via traps or at a convenient time via status flags. Traps can be used to stop a program, but unrecoverable situations are extremely rare. Simply stopping a program is not an option for embedded systems or network agents. More often, traps log diagnostic information or substitute valid results.
Flags offer both predictable control flow and speed. Their use requires the programmer be aware of exceptional conditions, but flag stickiness allows programmers to delay handling exceptional conditions until necessary.
An error is an appropriate response when dealing with numbers that do not have such capabilities, such as integral division.
这篇关于为什么NumPy浮动不能给ZeroDivisionError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!