gpt4 book ai didi

python - 为什么 NumPy float 不给出 ZeroDivisionError?

转载 作者:太空狗 更新时间:2023-10-30 00:28:08 26 4
gpt4 key购买 nike

我注意到在代码中:

import numpy as np    

a = 0.0
print a / a

b = np.array( [0.0] )
print b[0] / b[0]

第一个打印函数抛出 ZeroDivisionError,但第二个输出 nan。我知道 type(b[0])numpy.float64,而 type(a)float。我有两个问题:

1) 为什么要这样实现?

2) 无论如何让它抛出 ZeroDivisionError 吗?

最佳答案

我必须说,我更惊讶的是常规 Python float 确实会抛出错误。据我所知,鉴于 IEEE 754 中定义的 float ,返回 NaN 是正确的方法。

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 NaNs 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.

在处理不具有此类功能的数字(例如整数除法)时,错误是一种适当的响应。

关于python - 为什么 NumPy float 不给出 ZeroDivisionError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20670145/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com